<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/6
 * Time: 12:03
 */

namespace App\Http\Controllers\Home;

use App\Model\Apply;
use App\Model\BankCard;
use App\Model\DirectWeighting;
use App\Model\ExceedShop;
use App\Model\GroupList;
use App\Model\GroupMember;
use App\Model\Members;
use App\Model\MemberSign;
use App\Model\MembersLevel;
use App\Model\MicroMall;
use App\Model\Notice;
use App\Model\PartnerRecord;
use App\Model\Poundage;
use App\Model\RecordBonus;
use App\Model\RecordList;
use App\Model\RecordrRecharge;
use App\Model\RecordTransaction;
use App\Model\RecordTransferAccounts;
use App\Model\RecordWithdraw;
use App\Model\Reply;
use App\Model\SetBonus;
use App\Model\SetPartner;
use App\Model\SetQuality;
use App\Model\SetRead;
use App\Model\SetRebate;
use App\Model\SetrebateCompany;
use App\Model\ShopMemberCart;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use App\Model\ShoppingGoods;
use App\Model\StoreGoodsSet;
use App\Model\StoresCenter;
use App\Model\StoresCenterGoods;
use App\Model\StoresProfitRecord;
use App\Model\StraightShopp;
use App\Model\GoodsSpecsVal;
use App\Model\GoodsSpecsName;
use App\Model\Transaction;
use fast\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Model\Address;
use App\Model\ShopGoodsImg;
use App\Model\ShopGoods;
use Illuminate\Support\Facades\DB;
use PhpParser\Node\Expr\Empty_;
use Session;
use Log;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;

ini_set('max_execution_time', 0);

class MemberController extends BaseController
{
    /**
     * 会员中心
     */
    public function index()
    {
        //检测是否填写资料
        $user = session('home_user');
        $UserModel = new Members();
        $userInfo = $UserModel->where('uid', $user['uid'])->first();
        if ($userInfo['voucher'] == '') {
            $userInfo['voucher'] = '0.00';
        }
        $count = SetRebate::where(['name' => $userInfo['name'], 'status' => 1, 'type' => 1])->count();
        if ($count >= 1) {
            $userInfo['super_level_name'] = '合伙人';
        }
        Session::put('home_user', $userInfo);
        if (empty($userInfo['phone']) || empty($userInfo['user_name'])) {
            return redirect('home/member/userInfo')->withErrors('请完善个人资料');
        }
        return view('Home.member.user');
    }

    /**
     * 注册会员
     */
    public function registerUser()
    {
        return view('Home.member.registerUser');
    }

    /**
     * 商城伙伴列表
     */
    public function partnersList()
    {
        return view('Home.member.partnersList');
    }

    public function myPartners(Request $request)
    {
        $time = time();
        $user = session('home_user');
        $userUid = $request->get('id');
        if (empty($userUid)) {
            $userUid = $user->uid;
        }
        $useInfo = Members::where('uid', $userUid)->first()->toArray();
        $userData = Members::where('referrer', $userUid)->get(['uid', 'user_name', 'name', 'referrer'])->toArray();
        $data = [];
        $edges = [];
        foreach ($userData as $key => $value) {
            $uid[0] = $value['uid'];
            $Alluser = Members::where('uid', '>', $value['uid'])->get(['referrer', 'uid'])->toArray();
            $this->PartnersNum($Alluser, $uid, 0);
            $pid = session('pid');
            $data[$key]['id'] = $value['uid'];
            $data[$key]['label'] = $value['user_name'];
            $edges[$key]['from'] = $value['referrer'];
            $edges[$key]['to'] = $value['uid'];
        }
        array_push($data, ['id' => $userUid, 'label' => $useInfo['user_name'] . "\n" . $useInfo['name']]);
        $data = json_encode($data, true);
        $edges = json_encode($edges, true);
        return view('Home.member.myPartners', ['data' => $data, 'edges' => $edges]);
    }


    /**
     * 开通超级商城
     */
    public function openShop()
    {
        exit;
        $user = session('home_user');
        $userUid = $user->uid;
        $userDatas = Members::where('uid', $userUid)->first();
        if ($userDatas['isdown'] == 1) {
            echo "<script>alert('已经开通');location.href='/home/member/index';</script>";
            exit;
        } else {
            $userData = Members::where('referrer', $userUid)->get();
            $super_recommend = count($userData);//直推人数
            $data = [];
            foreach ($userData as $key => $value) {
                $uid[0] = $value['uid'];
                $Alluser = Members::where('uid', '>', $value['uid'])->get();
                $this->PartnersNum($Alluser, $uid, 0);
                $pid = session('pid');
                $money = session('money');
                $data[$key]['id'] = $value['uid'];
                $data[$key]['name'] = $value['user_name'];
                $data[$key]['number'] = $pid;
                $data[$key]['money'] = $money;
            }

            $super['super_recommend'] = 0; //超级商城 推荐人数
            $super['super_team_count'] = 0; //团队数量
            $super['isdown'] = 1; //'超级商城开关 1开 2关
            if ($data) {
                //排序
                $arrSort = array();
                foreach ($data as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                array_multisort($arrSort['number'], constant('SORT_DESC'), $data);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($data as $items => $item) { //上级V3
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['number'];
                    } else {
                        $big_num = $item['number'];
                    }
                }
                $super_team_count = $counts + $big_num; //总人数
                $super['super_recommend'] = $super_recommend; //超级商城 推荐人数
                $super['super_team_count'] = $super_team_count; //团队数量
            }
            if ($super_recommend > 9) {
                if ($counts >= 150 && $big_num >= 150) {
                    $super['super_level_name'] = 'V3'; //更改等级名字
                    $super['super_level'] = 3;//更改等级
                } else {
                    if ($super_team_count > 51) {
                        $super['super_level_name'] = 'V2'; //更改等级名字
                        $super['super_level'] = 2;//更改等级
                    } else {
                        $super['super_level_name'] = 'V1'; //更改等级名字
                        $super['super_level'] = 1;//更改等级
                    }
                }
            } else {
                $super['super_level_name'] = 'V1'; //更改等级名字
                $super['super_level'] = 1;//更改等级
            }
            $rico = Members::where('uid', $userUid)->update($super);
            if ($rico) {
                echo "<script>alert('开通成功');location.href='/home/member/index'; </script>";
            } else {
                echo "<script>alert('开通失败');location.href='/home/member/index';</script>";
            }
        }

    }

    /**
     *统计数量
     */

    public function PartnersNum($data = array(), $uid = array(), $pid = 0, $moeny = 0)
    {

        $nodesid = [];
        foreach ($data as $k => $v) {
            foreach ($uid as $key => $value) {
                if ($v['referrer'] == $value) {
                    $pid = empty($pid) ? 1 : $pid + 1;
                    $nodesid[] = $v['uid'];

                }
            }
        }
        if (!empty($nodesid)) {
            $this->PartnersNum($data, $nodesid, $pid, $moeny);
        } else {
            //保存session
            Session::put('pid', $pid);
        }
    }

    /**
     * 超级商城保单商品
     *
     */
    public function goods()
    {
        $where = [
            'type' => 1,
            'status' => 1,
            'cid' => 6,
        ];

        $good = ShopGoods::where($where)->get(['goodsname', 'id'])->toArray();

        if ($good) {
            return ['code' => 1, 'data' => $good];
        } else {
            return ['code' => 0, 'data' => '暂无可保单商品！'];
        }
    }

    /**
     * 门店是否存在
     */
    public function storeInformation(Request $request)
    {
        $data = $request->all();
        if ($data['storeNumber']) {
            //查询该门店是否存在
            $thisStoreExist = StoresCenter::where(['number' => $data['storeNumber'], 'type' => 1])->first();
            if (!$thisStoreExist) {
                return ['code' => 0, 'data' => '该门店编号不存在！'];
            } else {
                $thisStoreExist['address'] = $thisStoreExist['province'] . $thisStoreExist['city'] . $thisStoreExist['district'] . $thisStoreExist['address'];
                return ['code' => 1, 'data' => $thisStoreExist];
            }
        }
    }

    /**
     * 获取会员绑定门店信息
     * @param Request $request
     * @return array
     */

    public function getUserBindNumber(Request $request)
    {
        $user = session('home_user');
        $data = $request->all();
        if ($user) {
            $storeNumber = Members::where('uid', $user['uid'])->value('stores_number');
            if ($storeNumber) {
                //查询该门店
                $thisStoreExist = StoresCenter::where(['number' => $storeNumber, 'type' => 1])->first();
                $thisStoreExist['address'] = $thisStoreExist['province'] . $thisStoreExist['city'] . $thisStoreExist['district'] . $thisStoreExist['address'];
                $thisStoreExist['stores_number'] = $storeNumber;
                return ['code' => 1, 'data' => $thisStoreExist];
            }
        }
    }

    /**
     * 报单商城处理注册
     * @param Request $request
     * @return array
     */
    public function doRegisterUser(Request $request)
    {

        $data = $request->get('users');
        $again = $request->get('again');
        $goodsid = $request->get('goodsid');
        $level = $request->get('level');
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        };
        //判断联系人
        if (empty($data['phone'])) {
            return ['code' => 0, 'data' => '联系人电话不能为空'];
        };
        //判断联系人姓名
        if (empty($data['name'])) {
            return ['code' => 0, 'data' => '联系人姓名不能为空'];
        };
//        if (empty($data['code'])) {
//            return ['code' => 0, 'data' => '验证码不能为空'];
//        };
//        $rand = Session::get('register_code' . $data['phone'])['rand'];
//
//        if ($rand != intval($data['code'])) {
//            return ['code' => 0, 'data' => '验证码不正确！'];
//        }
        //判断是否选中商品
        if (empty($goodsid)) {
            return ['code' => 0, 'data' => '报单商品不能为空'];
        }
        //判断分享人电话
        if (empty($data['referrer'])) {
            return ['code' => 0, 'data' => '分享人电话不能为空'];
        };

        //会员表
        $UserModel = new Members();
        //门店奖励记录
        $StoresProfitRecordModel = new StoresProfitRecord();
        //判断分享人是否存在
        $referrer = $UserModel->where(['name' => $data['referrer']])->first();
        if (empty($referrer)) {
            return ['code' => 0, 'data' => '分享人不存在'];
        }
        //判断用户电话是否注册
        $phone = $UserModel->where(['name' => $data['phone']])->count();
        if (!empty($phone)) {
            return ['code' => 0, 'data' => '电话已被注册'];
        }
        //接收门店编号
        $storeNumber = $data['storeNumber'] == '' ? '0' : $data["storeNumber"];
        //判断该门店是否存在
        if (!empty($storeNumber)) {
            //查询该门店是否存在
            $thisStoreExist = StoresCenter::where(['number' => $storeNumber, 'type' => 1])->first();
            if (!$thisStoreExist) {
                return ['code' => 0, 'data' => '该门店编号不存在！'];
            }
        }
        $user = session('home_user');
        $uid = $user->uid;
        $userDetail = $UserModel->where(['uid' => $uid])->first();
        //支付密码
        if (ENCRYPTION($data['zfpassword'], $userDetail['salting_pay']) != $userDetail['password_pay']) {
            return ['code' => 0, 'data' => '支付密码错误！'];
        }
        //商品表
        $ShopGoods = new ShopGoods();
        $goods = $ShopGoods->where(['id' => $goodsid])->first();
        //系统设置
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->where(['id' => 1])->first();
        //业绩设置
        $QualityModel = new SetQuality();
        $Quality = $QualityModel->get()->toArray();
        //订单详情表
        $ShopOrderCommentModel = new ShopOrderComment();
        //注册vip
        DB::beginTransaction();
        //订单价格
        $points = $goods['rulingprice'];
        //实际支付金额
        $money = $goods['pk_integral'];
        $rico = FIGURE($user['credit1'], $user['credit2'], $points);
        if ($rico['code'] == 0) {
            return ['code' => 0, 'data' => '余额不足'];
        }
        //个人消费加权分红
//        $voucher = RETAIN_TWO($points / $goods['rulingprice']);
        $random = RANDOM(); //秘钥
        $memberData = [
            'name' => $data['phone'],
            'user_name' => $data['name'],
            'phone' => $data['phone'],
            'password_pay' => ENCRYPTION(empty($data['password_pay']) ? $data['phone'] : $data['password_pay'], $random),
            'password' => ENCRYPTION(empty($data['password']) ? $data['phone'] : $data['password'], $random),
            'salting_pay' => $random,
            'salting' => $random,
            'enroll_time' => time(), //注册时间
            'activation_time' => time(), //激活时间
            'registered' => 1, //1 已激活 0 未激活
            'referrer' => $referrer['uid'], //分享人
            'straight_shop_isdown' => $referrer['straight_shop_isdown'], //直商城开关 1开 2关
            'feferrer_name' => $user['user_name'], //分享人姓名
            'aisle' => 1, // 1 报单商城
            'super_level' => $goods['level'], //报单商城等级
            'super_level_name' => $ExceedShop[$goods['level'] - 1]['vip_name'], //报单商城等级 名称
            'stores_number' => $storeNumber, //门店中心编号
//            'voucher' => $voucher,//获得加权积分
//            'credit3' => $points * 2,//出局上限
//            'credit4' => $goods['is_explosive'],//获得消费元宝积分
            'is_read' => 0,//观看广告资格
            'is_withdraw' => 1,//提现资格
            'level' => 0,//获得加权积分
            'level_name' => 0,//获得加权积分
            'level_grade' => 0,//获得加权积分
            'platform_profit' => 1,//获得加权积分
            'achievement' => $points,//获得加权积分
            'updated_at' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s')
        ];
        $memberId = $UserModel->insertGetId($memberData);
        if (empty($memberId)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '注册失败,重新注册'];
        }


        //添加会员收货地址
        $memberNewAddressData = [
            'uid' => $memberId,
            'phone' => $data['phone'],
            'name' => $data['name'],
            'province' => $data['province'],
            'city' => $data['city'],
            'district' => $data['district'],
            'address' => $data['address'],
            'default' => 1,
            'updated_at' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s'),
        ];
        $addressMolde = new Address();
        $AddressId = $addressMolde->insertGetId($memberNewAddressData);
        if (empty($AddressId)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '注册失败,重新注册'];
        }
        $mallNumData = $goods['goodsname'] . '：' . '1件';
        $mallData = [
            0 => [
                'goods_id' => $goodsid,
                'num' => 1
            ]
        ];
        $ordersn = ORDER_SN();
        $order = [
            'uid' => $memberId,
            'ordertype' => 2, //1 商城 2 新人专区
            'ordersn' => $ordersn,
            'price' => $points,
            'originalprice' => $points,
            'status' => 1,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
            'createtime' => time(),
            'paytime' => time(),
            'mall_goodsid' => $goodsid,
            'is_first' => 1,
            'freight' => $data['freight'],
            'stores_number' => $storeNumber,
            'addressid' => $AddressId,
            'receipt_name' => $data['name'],
            'receipt_adr' => $data['province'] . $data['city'] . $data['district'] . $data['address'],
            'receipt_phone' => $data['phone'],
            'mall_num' => $mallNumData,
            'mall_data' => serialize($mallData),
            'reward_money' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'],//实际支付情况
            'credit1_money' => $rico['data']['credit1'] ,//购物积分实际支付情况
            'credit2_money' =>  $rico['data']['credit2'],//奖金实际支付情况
            'updated_at' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s'),
        ];
        //订单表
        $ShopOrderModel = new ShopOrder();
        $ricoOrder = $ShopOrderModel->add_order($order);
        if (empty($ricoOrder)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '交易失败'];
        }
        $orderComment = [
            'uid' => $user->uid,
            'orderid' => $ricoOrder,
            'openid' => $user->openid,
            'goodsid' => $goodsid,
            'price' => $goods['rulingprice'],
            'goodsname' => $goods['goodsname'],
            'number' => 1,
            'specs' => '',
            'createtime' => time(),
        ];

        $result = $ShopOrderCommentModel->insertGetId($orderComment);
        if (empty($result)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '交易失败'];
        }

        $this->credit2Record($ordersn, $uid);
        //扣除当前登录的金额
        $userData = [  //推荐人奖励添加 DATA
            'credit1' => $userDetail['credit1'] - $rico['data']['credit1'],
            'credit2' => $userDetail['credit2'] - $rico['data']['credit2'],

        ];
        $userOrder = $UserModel->where(['uid' => $uid])->update($userData);
        if (empty($userOrder)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '交易失败'];
        }
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        $recommendData = [
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => -$points,
            'type' => 1,
            'time' => time(),
            'explain' => '新人专区(不可退货)',
            'remark' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'],
        ];


        $TransactionId = $RecordTransaction->add_transaction($recommendData);
        if (empty($TransactionId)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '交易失败'];
        }

//        $RecordTransaction = new RecordTransaction();
//        $recommendData = [
//            'uid' => $memberId,
//            'ordersn' => $ordersn,
//            'money' => $voucher,
//            'type' => 1,
//            'time' => time(),
//            'explain' => '个人消费积分份额',
//            'remark' => '个人消费积分份额：' . $voucher,
//        ];
//        $TransactionId = $RecordTransaction->add_transaction($recommendData);
//        if (empty($TransactionId)) {
//            DB::rollback();  //回滚
//            return ['code' => 0, 'data' => '交易失败'];
//        }
//        if ($referrer['super_recommend'] <= 5) {
        //直推消费加权积分
//        $referrer_voucher = RETAIN_TWO($Poundage['share'] * $voucher / 100);
//        if (!$referrer_voucher) {
//            DB::rollback();  //回滚
//            return ['code' => 0, 'data' => '数据错误'];
//        } else {
//            //
//            $shareData = [  //推荐人奖励添加 DATA
//                'voucher' => $referrer['voucher'] + $referrer_voucher,
//            ];
//            $userOrder = $UserModel->where(['uid' => $referrer['uid']])->update($shareData);
//            if (!$userOrder) {
//                DB::rollback();  //回滚
//                return ['code' => 0, 'data' => '交易失败'];
//            }
//            //交易记录表
//            $RecordTransaction = new RecordTransaction();
//            $recommendData = [
//                'uid' => $referrer['uid'],
//                'ordersn' => $ordersn,
//                'money' => $referrer_voucher,
//                'type' => 1,
//                'time' => time(),
//                'explain' => '消费推荐积分',
//                'remark' => '消费推荐积分：' . $referrer_voucher,
//            ];
//            $TransactionId = $RecordTransaction->add_transaction($recommendData);
//            if (empty($TransactionId)) {
//                DB::rollback();  //回滚
//                return ['code' => 0, 'data' => '交易失败'];
//            }
//        }

        //个人消费e+积分明细
//        if ($goods['is_explosive'] > 0) {
//            $RecordTransaction = new RecordTransaction();
//            $recommendData = [
//                'uid' => $memberId,
//                'ordersn' => $ordersn,
//                'money' => $goods['is_explosive'],
//                'type' => 4,
//                'time' => time(),
//                'explain' => '个人消费e+积分',
//                'remark' => '个人消费e+积分：' . $goods['is_explosive'],
//            ];
//            $TransactionId = $RecordTransaction->add_transaction($recommendData);
//            if (empty($TransactionId)) {
//                DB::rollback();  //回滚
//                return ['code' => 0, 'data' => '交易失败'];
//            }
//
//
//        }
////       直推奖励
//        $ExceedShopModel = new ExceedShop();
//        $ExceedShop = $ExceedShopModel->where(['id' => 1])->first();
//        if ($ExceedShop['vip'] > 0) {
//            $referrer_data = $UserModel->where(['uid' => $referrer['uid']])->first();
//            $money1 = RETAIN_TWO($money * ($ExceedShop['vip'] * 0.01));
//            $recommendMoney = CALCULATE($Poundage, $money1, 1);
//            $referrer_direct = [  //推荐人奖励添加 DATA
//                'credit2' => $referrer_data['credit2'] + $recommendMoney['money'],
//                'credit5' => $referrer_data['credit5'] + $recommendMoney['redelivery'],
//            ];
//            $result = $UserModel->where(['uid' => $referrer['uid']])->update($referrer_direct);
//            if ($result) {
//                //添加记录
//                $this->bonusCredit2($referrer_data['uid'], $ordersn);
//                $this->addOrder($referrer['uid'], $money1, 5, '报单直推奖', $recommendMoney, 1, $order['ordersn']);
//            }
//        }

        $bonusModel = new SetBonus();
        $setBonus = $bonusModel->get()->toArray();
        $super = $this->superShop($memberId, $referrer['uid'], $Quality, $goods['level'], $Poundage, $points, $ordersn, $money, $setBonus);
        if (empty($super)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '奖金计算失败'];
        }
        //补贴分红奖金池金额
        $set_money = RETAIN_TWO($points * $Poundage['set_order_consumption'] / 100);
        $set = $PoundageModel->where('id', 1)->update(['subsidy_reward' => $Poundage['subsidy_reward'] + $set_money]);
        if (empty($set)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '奖金池金额统计失败！！!'];
        }
        //总公司合伙人分红
        if ($money > 0) {
            $applyModel = new SetrebateCompany();
            $partners = $applyModel->where(['is_one' => 1, 'status' => 1])->get()->toArray();//一级核心人员
            $service = $applyModel->where(['is_two' => 1, 'status' => 1])->get()->toArray();
            $ceo = $applyModel->where(['is_three' => 1, 'status' => 1])->get()->toArray();
            $ser_count = count($service);
            $count = count($partners);
            $ceo_count = count($ceo);
            if ($count == 0) {
                $Poundage['is_one'] = 0;
            }
            if ($ser_count == 0) {
                $Poundage['is_two'] = 0;
            }
            if ($ceo_count == 0) {
                $Poundage['is_three'] = 0;
            }
            //总公司一级合伙人分红
            if ($Poundage['is_one'] > 0) {
                if ($count > 0) {
                    foreach ($partners as $k => $v) {
                        $partner = Members::where('name', $v['name'])->first();
                        $money2 = RETAIN_TWO($money * $Poundage['is_one'] / 100 / $count);
                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
                        //添加记录
                        if ($partner['type'] == 1) {
                            $partner['credit2'] += $recommendMoney['money'];
                            $partner['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $partner['uid'])->update(['credit2' => $partner['credit2'], 'credit5' => $partner['credit5']]);
                            $this->credit2Record($order['ordersn'], $partner['uid']);
                            //重新赋值
                            $addData3['money'] = $money2;
                            $addData3['type'] = 5;
                            $addData3['text'] = '总公司一级合伙人分润';
                            $addData3['recommendMoney'] = $recommendMoney;
                            $addData3['ordersn'] = $order['ordersn'];
                            if ($res) {
                                $this->addOrder($partner['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
                            }
                        }
                    }
                }
            }

            //总公司二级合伙人分红
            if ($Poundage['is_two'] > 0) {
                if ($ser_count > 0) {
                    foreach ($service as $k => $v) {
                        $ser = Members::where('name', $v['name'])->first();
                        $money3 = RETAIN_TWO($money * $Poundage['is_two'] / 100 / $ser_count);
                        $recommendMoney = CALCULATE($Poundage, $money3, 2);
                        //添加记录
                        if ($ser['type'] == 1) {
                            $ser['credit2'] += $recommendMoney['money'];
                            $ser['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $ser['uid'])->update(['credit2' => $ser['credit2'], 'credit5' => $ser['credit5']]);
                            $this->credit2Record($order['ordersn'], $ser['uid']);
                            //重新赋值
                            $addData4['money'] = $money3;
                            $addData4['type'] = 5;
                            $addData4['text'] = '总公司二级合伙人分润';
                            $addData4['recommendMoney'] = $recommendMoney;
                            $addData4['ordersn'] = $order['ordersn'];
                            if ($res) {
                                $this->addOrder($ser['uid'], $addData4['money'], 5, $addData4['text'], $addData4['recommendMoney'], 0, $addData4['ordersn']);
                            }
                        }
                    }
                }
            }
            //总公司三级合伙人分红
            if ($Poundage['is_three'] > 0) {
                if ($ceo_count > 0) {
                    foreach ($ceo as $k => $v) {
                        $user = Members::where('name', $v['name'])->first();
                        $money4 = RETAIN_TWO($money * $Poundage['is_three'] / 100 / $ceo_count);
                        $recommendMoney = CALCULATE($Poundage, $money4, 2);
                        //添加记录
                        if ($user['type'] == 1) {
                            $user['credit2'] += $recommendMoney['money'];
                            $user['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $user['uid'])->update(['credit2' => $user['credit2'], 'credit5' => $user['credit5']]);
                            $this->credit2Record($order['ordersn'], $user['uid']);
                            //重新赋值
                            $addData5['money'] = $money4;
                            $addData5['type'] = 5;
                            $addData5['text'] = '总公司三级合伙人分润';
                            $addData5['recommendMoney'] = $recommendMoney;
                            $addData5['ordersn'] = $order['ordersn'];
                            if ($res) {
                                $this->addOrder($user['uid'], $addData5['money'], 5, $addData5['text'], $addData5['recommendMoney'], 0, $addData5['ordersn']);
                            }
                        }
                    }
                }
            }


        }
        //计算门店中心收益
        if ($storeNumber != '0') {
            //门店收益
            $this->StoresCenter($money, $Poundage, $ordersn, $storeNumber);
            $storeUid = StoresCenter::where('number', $storeNumber)->value('uid');
            //减少用户消费门店的对应商品的库存
            foreach ($mallData as $k => $v) {
                if ($v['num'] != '0') {
                    $storeGoodsNumber = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])
                        ->select('goodsname', 'inventory', 'specs_txt')
                        ->first();
                    if ($storeGoodsNumber["inventory"] <= 0 || $storeGoodsNumber["inventory"] < $v['num']) {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '该门店商品:' . $storeGoodsNumber["goodsname"] . '库存不足,请提醒商家加货!'];
                        exit;
                    }
                    //减少该门店对应商品的现库存量
                    $StoreInventoryDel = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->decrement('inventory', $v['num']);
                    //增加该门店对应商品的已出售量
                    $StoreSoldAdd = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->increment('sold', $v['num']);
                    //增加门店可补货金额
                    $StoreInvoiceAdd = StoresCenter::where(['number' => $storeNumber])->increment('invoices', $money);
                    if (!$StoreInventoryDel || !$StoreSoldAdd || !$StoreInvoiceAdd) {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '门店商品库存变更失败！'];
                        exit;
                    }
                }
            }
            //增加一条终身绑定门店个人账户奖励币增加的记录
            $firstUidTransactionData = [
                'uid' => $storeUid,
                'ordersn' => $ordersn,
                'money' => RETAIN_TWO($points * $Poundage['bind_store'] / 100),
                'type' => 5,
                'time' => time(),
                'explain' => '会员注册',
                'remark' => '终生绑定门店收益'
            ];
            $bindStoreCredit2 = Members::where(['uid' => $storeUid])->value('credit2');
            $bindStoreCredit2Add = Members::where(['uid' => $storeUid])->update(['credit2' => $bindStoreCredit2 + $firstUidTransactionData['money']]);
            if (!$bindStoreCredit2Add) {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '终身绑定门店个人账户奖励币增加失败！'];
            }
            $StoreFirstTransaction = $RecordTransaction->add_transaction($firstUidTransactionData);
            if (!$StoreFirstTransaction) {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '终身绑定门店个人账户奖励币记录增加失败！'];
            }

            $firstSource = "姓名为" . $user["user_name"] . "，电话号码为" . $user["phone"] . "的用户在服务中心为手机号" . $data['phone'] . "进行了会员报单，共" . $money . "元";

            $firstSourceStore = "姓名为" . $user["user_name"] . "，电话号码为" . substr_replace($user["phone"], '****', 3, 4) . "的用户在服务中心为手机号" . $data['phone'] . "进行了会员报单，共" . $money . "元";

            $firstStoreCurrency = RETAIN_TWO($points * $Poundage['store'] / 100);

            $firstStoreNumber = $storeNumber;

            //插入一条终身绑定门店返币收益记录
            $firstStoreProfitRecord = $StoresProfitRecordModel->add(['store_number' => $firstStoreNumber, 'currency' => $firstStoreCurrency, 'source' => $firstSource, 'source_store' => $firstSourceStore, 'addtime' => time(), 'profit_type' => 1, 'consum_type' => 1, 'ordersn' => $ordersn]);
            if (!$firstStoreProfitRecord) {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '终身绑定门店收益记录添加失败！'];
            }

        }
        //全国门店加权分润
        $stores = StoresCenter::where('type', 1)->get()->toArray();
        if (!empty($stores)) {
            $storeCount = count($stores);
            $storeMoney = RETAIN_TWO($money * $Poundage['store_platform'] / 100 / $storeCount);
            foreach ($stores as $k => $v) {
                $storeMember = Members::where('uid', $v['uid'])->select('credit1', 'credit2', 'credit3', 'credit4', 'credit5')->first();
                $recommendMoney = CALCULATE($Poundage, $storeMoney, 2);
                //扣除平台费和复投币
                $storeMember['credit2'] += $recommendMoney['money'];
                $storeMember['credit5'] += $recommendMoney['redelivery'];
                //添加记录
                $this->addOrder($v['uid'], $storeMoney, 5, '全国服务中心分润', $recommendMoney, 0, $ordersn);
                //更新会员数据
                $UserModel->where(['uid' => $v['uid']])->update($storeMember['attributes']);
            }
        }
        DB::commit();  //提交
        return ['code' => 1, 'data' => '支付成功，不可退货'];


    }

    /**
     *阅读得积分
     */
    public function readUser(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        $uid = $user->uid;
        $recExist = Transaction::where('uid', $uid)->where('type', 6)->orderBy('id', 'desc')->limit(1)->first();
        //判断上次得积分超过24小时
        if (!empty($recExist)) {
            $date = date("Y-m-d", strtotime($recExist['created_at']));
            if (strtotime($date) == strtotime(date("Y-m-d", strtotime("today")))) {
                return ['code' => 0, 'data' => '今日已阅读！！'];
            }
        }
        //会员表
        $UserModel = new Members();
        //阅读获得补贴资格
        $userData = [
            'is_read' => 1,
        ];
        $res = $UserModel->where('uid', $uid)->update($userData);
        $ordersn = ORDER_SN();
        if ($res) {
            //交易记录表详情表
            $RecordTransaction = new RecordTransaction();
            $rows = [ //交易记录
                'uid' => $uid,
                'ordersn' => $ordersn,
                'money' => '',
                'type' => 6,
                'time' => time(),
                'explain' => '观看广告',
                'remark' => '今日广告已看',
            ];
            $TransactionId = $RecordTransaction->add_transaction($rows);
            if ($TransactionId) {
                return ['code' => 1, 'data' => '恭喜你获得广告补贴资格,请再接再厉'];
            }

        }

    }

    /**
     * 阅读积分奖励分配
     * @param $reader
     * @param $point
     * @param $setRead
     * @param $bookId
     * @param $ExceedShop
     * @param $Poundage
     * @param $ordersn
     * @return bool
     */
    public function readBonus($reader, $point, $setRead, $bookId, $ExceedShop, $Poundage, $ordersn)
    {

        $number1 = 1;
        $number2 = 1;
        $point2 = $point;
        $point3 = $point;
        $point4 = $point;
        $referrer = Members::where('uid', $reader['uid'])->value('referrer');
        $ricos = 1; //判断错误
        $arrays = [];
        //会员表
        $UserModel = new Members();
        $members = $UserModel->where('uid', '<=', $reader['uid'])->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();

        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {  //寻找上级id 微客
                    $referrer = $v['referrer'];
                    if ($v['super_level'] >= 1) {
                        if ($number1 <= 1) {
                            if ($ExceedShop[0]['read_award'] > 0) {
                                $point2 = RETAIN_TWO($ExceedShop[0]['read_award'] * $point / 100);
//                                $recommendMoney = CALCULATE($Poundage, $point2, 2);
                                $number1++;
                                //添加记录
                                $v['credit4'] += $point2;
//                                $v['credit5'] += $recommendMoney['redelivery'];
                                $v['addData']['addData1']['money'] = $point2;
                                $v['addData']['addData1']['type'] = 5;
                                $v['addData']['addData1']['text'] = '直推阅读积分分享';
                                $v['addData']['addData1']['recommendMoney'] = $point2;
                                $v['addData']['addData1']['company_id'] = $bookId;
                                $v['addData']['addData1']['ordersn'] = $ordersn;
                            }
                        }
                    }
                    if ($v['super_level'] >= 2) {
                        if ($number2 <= 2) {
                            if ($number2 == 1) {
                                if ($ExceedShop[1]['read_award'] > 0) {
                                    $point3 = RETAIN_TWO($ExceedShop[1]['read_award'] * $point / 100);
//                                    $recommendMoney = CALCULATE($Poundage, $point3, 2);
                                    $number2++;
                                    //添加记录
                                    $v['credit4'] += $point3;
//                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $v['addData']['addData2']['money'] = $point3;
                                    $v['addData']['addData2']['type'] = 5;
                                    $v['addData']['addData2']['text'] = '二级阅读积分分享';
                                    $v['addData']['addData2']['recommendMoney'] = $point3;
                                    $v['addData']['addData2']['company_id'] = $bookId;
                                    $v['addData']['addData2']['ordersn'] = $ordersn;
                                }

                            } else {
                                if ($ExceedShop[1]['read_leve']) {
                                    $point4 = RETAIN_TWO($ExceedShop[1]['read_leve'] * $point3 / 100);
//                                    $recommendMoney = CALCULATE($Poundage, $point4, 2);
                                    $number2++;
                                    //添加记录
                                    $v['credit4'] += $point4;
//                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $v['addData']['addData2']['money'] = $point4;
                                    $v['addData']['addData2']['type'] = 5;
                                    $v['addData']['addData2']['text'] = '二级平级阅读积分分享';
                                    $v['addData']['addData2']['recommendMoney'] = $point4;
                                    $v['addData']['addData2']['company_id'] = $bookId;
                                    $v['addData']['addData2']['ordersn'] = $ordersn;
                                }

                            }
                        }
                    }

                    //上级uid
                    $puid = $v['uid'];
                    //更新会员数据
                    if ($UserModel->where(['uid' => $v['uid']])->update(
                        [
                            'credit4' => $v['credit4'],
                            'credit5' => $v['credit5'],
                        ]
                    )
                    ) {
                        //添加记录
                        if (!empty($v['addData']['addData1'])) {
                            $this->addOrder($v['uid'], $v['addData']['addData1']['money'], 5, $v['addData']['addData1']['text'], $v['addData']['addData1']['recommendMoney'], 0, $v['addData']['addData1']['ordersn']);
                        }
                        if (!empty($v['addData']['addData2'])) {
                            $this->addOrder($v['uid'], $v['addData']['addData2']['money'], 5, $v['addData']['addData2']['text'], $v['addData']['addData2']['recommendMoney'], 0, $v['addData']['addData2']['ordersn']);
                        }
                        if (!empty($v['addData']['addData3'])) {
                            $this->addOrder($v['uid'], $v['addData']['addData3']['money'], 5, $v['addData']['addData3']['text'], $v['addData']['addData3']['recommendMoney'], 0, $v['addData']['addData3']['ordersn']);
                        }
                    } else {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 业绩奖励
     * @param null $uid
     * @param null $referrer
     * @param array $ExceedShop
     * @param null $money
     * @param string $ordersn
     * @param int $type
     * @return bool
     */
    public function achievementBonus($uid = null, $referrer = null, $ExceedShop = array(), $Poundage = array(), $money = null, $ordersn = '', $type = 0)
    {

        //会员表
        $UserModel = new Members();
        $order = ShopOrder::where('ordersn', $ordersn)->first();
        $share = $referrer;//分享人ID
        $puid = $uid;
        $money1 = $money;
        $money2 = $money;
        $money3 = $money;
        $money4 = $money;
        $number1 = 1;
        $number2 = 1;
        $number3 = 1;
        $number4 = 1;
        $members = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'credit2', 'credit5', 'type')->get()->toArray();
        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {//寻找上级id 微客
                    $referrer = $v['referrer'];
                    $credit2 = $v['credit2'];
                    //V1业绩奖
                    if ($v['level'] >= 1) {
                        if ($number1 <= 2) {
                            if ($number1 == 1) {
                                $money1 = RETAIN_TWO($ExceedShop[0]['reword'] * $money / 100);
                                $recommendMoney = CALCULATE($Poundage, $money1, 2);
                                ++$number1;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData1']['money'] = $money1;
                                    $v['addData']['addData1']['type'] = 5;
                                    $v['addData']['addData1']['text'] = 'V1团队奖';
                                    $v['addData']['addData1']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData1']['ordersn'] = $ordersn;
                                }
                            } else {
                                $money1 = RETAIN_TWO($ExceedShop[0]['flat'] * $money1 / 100);
                                $recommendMoney = CALCULATE($Poundage, $money1, 2);
                                ++$number1;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData1']['money'] = $money1;
                                    $v['addData']['addData1']['type'] = 5;
                                    $v['addData']['addData1']['text'] = 'V1团队平级奖';
                                    $v['addData']['addData1']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData1']['ordersn'] = $ordersn;
                                }
                            }
                        }
                    }
                    //V2业绩奖
                    if ($v['level'] >= 2) {
                        if ($number2 <= 2) {
                            if ($number2 == 1) {
                                $money2 = RETAIN_TWO($ExceedShop[1]['reword'] * $money / 100);
                                $recommendMoney = CALCULATE($Poundage, $money2, 2);
                                ++$number2;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData2']['money'] = $money1;
                                    $v['addData']['addData2']['type'] = 5;
                                    $v['addData']['addData2']['text'] = 'V2团队奖';
                                    $v['addData']['addData2']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData2']['ordersn'] = $ordersn;
                                }
                            } else {
                                $money2 = RETAIN_TWO($ExceedShop[1]['flat'] * $money2 / 100);
                                $recommendMoney = CALCULATE($Poundage, $money2, 2);
                                ++$number2;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData2']['money'] = $money2;
                                    $v['addData']['addData2']['type'] = 5;
                                    $v['addData']['addData2']['text'] = 'V2团队平级奖';
                                    $v['addData']['addData2']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData2']['ordersn'] = $ordersn;
                                }
                            }
                        }
                    }
                    //V3业绩奖
                    if ($v['level'] >= 3) {
                        if ($number3 <= 2) {
                            if ($number3 == 1) {
                                $money3 = RETAIN_TWO($ExceedShop[2]['reword'] * $money / 100);
                                $recommendMoney = CALCULATE($Poundage, $money3, 2);
                                ++$number3;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData3']['money'] = $money3;
                                    $v['addData']['addData3']['type'] = 5;
                                    $v['addData']['addData3']['text'] = 'V3团队奖';
                                    $v['addData']['addData3']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData3']['ordersn'] = $ordersn;
                                }
                            } else {
                                $money3 = RETAIN_TWO($ExceedShop[2]['flat'] * $money3 / 100);
                                $recommendMoney = CALCULATE($Poundage, $money3, 2);
                                ++$number3;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData3']['money'] = $money3;
                                    $v['addData']['addData3']['type'] = 5;
                                    $v['addData']['addData3']['text'] = 'V3团队平级奖';
                                    $v['addData']['addData3']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData3']['ordersn'] = $ordersn;
                                }
                            }
                        }
                    }
                    //V4业绩奖
                    if ($v['level'] >= 4) {
                        if ($number4 <= 2) {
                            if ($number4 == 1) {
                                $money4 = RETAIN_TWO($ExceedShop[3]['reword'] * $money / 100);
                                $recommendMoney = CALCULATE($Poundage, $money4, 2);
                                ++$number4;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData4']['money'] = $money4;
                                    $v['addData']['addData4']['type'] = 5;
                                    $v['addData']['addData4']['text'] = 'V4团队奖';
                                    $v['addData']['addData4']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData4']['ordersn'] = $ordersn;
                                }
                            } else {
                                $money4 = RETAIN_TWO($ExceedShop[3]['flat'] * $money4 / 100);
                                $recommendMoney = CALCULATE($Poundage, $money4, 2);
                                ++$number4;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //记录订单之前各会员的奖励币余额记录
                                    $this->credit2Record($ordersn, $v['uid']);
                                    //重新赋值
                                    $v['addData']['addData4']['money'] = $money4;
                                    $v['addData']['addData4']['type'] = 5;
                                    $v['addData']['addData4']['text'] = 'V4团队平级奖';
                                    $v['addData']['addData4']['recommendMoney'] = $recommendMoney;
                                    $v['addData']['addData4']['ordersn'] = $ordersn;
                                }
                            }
                        }
                    }
                    //上级uid
                    $puid = $v['uid'];
                    //更新会员数据
                    if ($credit2 != $v['credit2']) {
                        $res = $UserModel->where(['uid' => $v['uid']])->update(
                            [
                                'credit2' => $v['credit2'],
                                'credit5' => $v['credit5']
                            ]
                        );
                        if ($res) {
                            //添加记录
                            if (!empty($v['addData']['addData1'])) {
                                $this->addOrder($v['uid'], $v['addData']['addData1']['money'], 5, $v['addData']['addData1']['text'], $v['addData']['addData1']['recommendMoney'], 0, $v['addData']['addData1']['ordersn']);
                            }
                            if (!empty($v['addData']['addData2'])) {
                                $this->addOrder($v['uid'], $v['addData']['addData2']['money'], 5, $v['addData']['addData2']['text'], $v['addData']['addData2']['recommendMoney'], 0, $v['addData']['addData2']['ordersn']);
                            }
                            if (!empty($v['addData']['addData3'])) {
                                $this->addOrder($v['uid'], $v['addData']['addData3']['money'], 5, $v['addData']['addData3']['text'], $v['addData']['addData3']['recommendMoney'], 0, $v['addData']['addData3']['ordersn']);
                            }
                            if (!empty($v['addData']['addData4'])) {
                                $this->addOrder($v['uid'], $v['addData']['addData4']['money'], 5, $v['addData']['addData4']['text'], $v['addData']['addData4']['recommendMoney'], 0, $v['addData']['addData4']['ordersn']);
                            }
                        } else {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 复销支付订单
     * @param Request $request
     */
    public function addMicro(Request $request)
    {
        $data = $request->all();
        $arrays = [];
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        if (!$data['addressid']) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //接收门店编号
        $storeNumber = $data['storeNumber'] == '' ? '0' : $data["storeNumber"];
        //判断该门店是否存在
        if (!empty($storeNumber)) {
            //查询该门店是否存在
            $thisStoreExist = StoresCenter::where(['number' => $storeNumber, 'type' => 1])->first();
            if (!$thisStoreExist) {
                return ['code' => 0, 'data' => '该门店编号不存在！'];
            }
        }
        $latitudes = $request->get('latitudes');
        $specs = $request->get('specs');
        //订单id
        $id = $data['id'];
        //会员表
        $UserModel = new Members();
        $RecordTransaction = new RecordTransaction();
        $RecordTransaction = new RecordTransaction();
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->where('id', 1)->first();
        $StoresProfitRecordModel = new StoresProfitRecord();
        $user = session('home_user');
        $uid = $user->uid;
        $referrer = $user->referrer;
        $share = $referrer;//分享人ID
        $puid = $uid;
        $user = $UserModel->where(['uid' => $user->uid])->first();
        //支付密码
        if (ENCRYPTION($data['zfpassword'], $user['salting_pay']) != $user['password_pay']) {
            return ['code' => 0, 'data' => '支付密码错误！'];
        }
        $company_id = $user['company_id'];
        //订单表
        $ShopOrder = new ShopOrder();
        $order = $ShopOrder->where(['id' => $id, 'uid' => $uid])->first();
        if (empty($order)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //订单金额
        $money = $order['price'];

        //实际分佣积分
        $bonus_points = 0;
        $orderComment = ShopOrderComment::where('orderid', $order['id'])->get()->toArray();
        foreach ($orderComment as $k => $v) {
            $costPrice = ShopGoods::where('id', $v['goodsid'])->value('pk_integral');

            $bonus_points += $costPrice * $v['number'];
        }
        //订单详情表
        $orderComment = ShopOrderComment::where(['orderid' => $id, 'uid' => $uid])->first();
        $is_throw = ShopGoods::where('id', $orderComment['goodsid'])->value('is_throw');
        //判断用户是否复消
        if ($data['again'] == 'true') {
            $rico = FIGURE_FUXIAO($user['credit1'], $user['credit2'], $user['credit5'], $money);
        } else {
            $rico = FIGURE($user['credit1'], $user['credit2'], $money);
        }
        $status = ShopOrder::where('id', $id)->select('status')->first();
        if (Session::has('orderPay' . $id) || $status->status == 1) {
            return ['code' => 0, 'data' => '支付中,请勿重复提交'];
        }
        if ($rico['code'] == 1) {
            //加权业绩设置
//            $bonusModel = new SetBonus();
//            $setBonus = $bonusModel->get()->toArray();
//            //系统设置
            $SetPoundage = new Poundage();
            $Poundage = $SetPoundage->where(['id' => 1])->first()->toArray();
            //微商城设置
            $microMall = new MicroMall();
            $micro = $microMall->where('id', 1)->first();
            //第一次请求  带上订单号存Sessoin
            Session::put('orderPay' . $id, $id);
            Session::save();
            DB::beginTransaction();
            if ($data['again'] == 'true') {
                //复消
                $userData = [
                    'credit1' => $user['credit1'] - $rico['data']['credit1'],
                    'credit2' => $user['credit2'] - $rico['data']['credit2'],
                    'credit5' => $user['credit5'] - $rico['data']['credit5'],
                    'achievement' => $user['achievement'] + $money,
                ];
            } else {
                $userData = [
                    'credit1' => $user['credit1'] - $rico['data']['credit1'],
                    'credit2' => $user['credit2'] - $rico['data']['credit2'],
                    'achievement' => $user['achievement'] + $money,

                ];
            }
            //绑定终生门店
            $userBindNumber = Members::where('uid', $uid)->value('stores_number');
            if (empty($userBindNumber) && $storeNumber != 0) {
                $userData['stores_number'] = $storeNumber;
                $bindStoreNumber = Members::where('uid', $uid)->update(['store_number' => $storeNumber]);
                if (!$bindStoreNumber) {
                    DB::rollback();
                    return ['code' => 0, 'data' => '绑定终生门店失败'];
                }
            }

            $this->credit2Record($order['ordersn'], $uid);
            $userOrder = $UserModel->where(['uid' => $uid])->update($userData);
            if (empty($userOrder)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $id);
                Session::save();
                return ['code' => 0, 'data' => '参数错误'];
            }
            //交易记录表
            $RecordTransaction = new RecordTransaction();
            if ($data['again'] == 'true') {
                $recommendData = [
                    'uid' => $uid,
                    'ordersn' => $order['ordersn'],//关联order表订单编号
                    'money' => -$money,
                    'type' => 1,
                    'time' => time(),
                    'explain' => '复销商城',
                    'company_id' => $company_id,
                    'remark' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'] . '，复销积分：' . -$rico['data']['credit5'],
                ];
                //修改订单状态
                $addressDataAdd = Address::where(['id' => $data['addressid']])->select('name', 'phone', 'province', 'city', 'district', 'address')->first();
                $saveOrder = $ShopOrder->where(['id' => $id])->update([
                    'status' => 1,
                    'paytime' => time(),
                    'reward_money' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'] . '，复销积分：' . -$rico['data']['credit5'],
                    'credit1_money' => $rico['data']['credit1'] ,
                    'credit2_money' => $rico['data']['credit2'] ,
                    'credit5_money' => $rico['data']['credit5'],
                    'addressid' => $data['addressid'],
                    'receipt_name' => $addressDataAdd['name'],
                    'receipt_adr' => $addressDataAdd['province'] . $addressDataAdd['city'] . $addressDataAdd['district'] . $addressDataAdd['address'], 'receipt_phone' => $addressDataAdd['phone']]);
                if (empty($saveOrder)) {
                    DB::rollback();  //回滚
                    Session::forget('orderPay' . $id);
                    Session::save();
                    return ['code' => 0, 'data' => '参数错误'];
                }
            } else {
                $recommendData = [
                    'uid' => $uid,
                    'ordersn' => $order['ordersn'],//关联order表订单编号
                    'money' => -$money,
                    'type' => 1,
                    'time' => time(),
                    'explain' => '复销商城',
                    'company_id' => $company_id,
                    'remark' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'],
                ];
                //修改订单状态
                $addressDataAdd = Address::where(['id' => $data['addressid']])->select('name', 'phone', 'province', 'city', 'district', 'address')->first();
                $saveOrder = $ShopOrder->where(['id' => $id])->update([
                    'status' => 1,
                    'paytime' => time(),
                    'reward_money' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'],
                    'credit1_money' => $rico['data']['credit1'] ,
                    'credit2_money' => $rico['data']['credit2'] ,
                    'addressid' => $data['addressid'],
                    'receipt_name' => $addressDataAdd['name'],
                    'receipt_adr' => $addressDataAdd['province'] . $addressDataAdd['city'] . $addressDataAdd['district'] . $addressDataAdd['address'], 'receipt_phone' => $addressDataAdd['phone']]);
                if (empty($saveOrder)) {
                    DB::rollback();  //回滚
                    Session::forget('orderPay' . $id);
                    Session::save();
                    return ['code' => 0, 'data' => '参数错误'];
                }
            }

            $TransactionId = $RecordTransaction->add_transaction($recommendData);
            if (empty($TransactionId)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $id);
                Session::save();
                return ['code' => 0, 'data' => '参数错误'];
            }

            if($data['again'] == 'true'){
                //个人消费元宝积分明细
                $is_explosive = RETAIN_TWO($rico['data']['credit5'] / 10);
                if ($is_explosive > 0) {
                    $credit4 = $UserModel->where(['uid' => $uid])->increment('voucher', $is_explosive);
                    if ($credit4) {
                        $RecordTransaction = new RecordTransaction();
                        $recommendData = [
                            'uid' => $uid,
                            'ordersn' => $order['ordersn'],
                            'money' => $is_explosive,
                            'type' => 4,
                            'time' => time(),
                            'explain' => '个人复购贡献值',
                            'remark' => '个人复购贡献值：' . $is_explosive,
                        ];
                        $TransactionId = $RecordTransaction->add_transaction($recommendData);
                        if (empty($TransactionId)) {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '交易失败'];
                        }
                    }

                }
            }

            // 复销奖金计算
            $mic = $this->bonusMicro($uid, $user['referrer'], $micro, $Poundage, $money, 0, $order['ordersn'], $bonus_points);
            if (empty($mic)) {
                DB::rollback();
                return ['code' => 0, 'data' => '奖金计算失败'];
            }

            if (!empty($bonus_points)) {
                $applyModel = new SetrebateCompany();
                $partners = $applyModel->where(['is_one' => 1, 'status' => 1])->get()->toArray();//一级核心人员
                $service = $applyModel->where(['is_two' => 1, 'status' => 1])->get()->toArray();
                $ceo = $applyModel->where(['is_three' => 1, 'status' => 1])->get()->toArray();
                $ser_count = count($service);
                $count = count($partners);
                $ceo_count = count($ceo);
                if ($count == 0) {
                    $Poundage['is_one'] = 0;
                }
                if ($ser_count == 0) {
                    $Poundage['is_two'] = 0;
                }
                if ($ceo_count == 0) {
                    $Poundage['is_three'] = 0;
                }
                //总公司一级合伙人分红
                if ($Poundage['is_one'] > 0) {
                    if ($count > 0) {
                        foreach ($partners as $k => $v) {
                            $partner = Members::where('name', $v['name'])->first();
                            $money2 = RETAIN_TWO($bonus_points * $Poundage['is_one'] / 100 / $count);
                            $recommendMoney = CALCULATE($Poundage, $money2, 2);
                            //添加记录
                            if ($partner['type'] == 1) {
                                $partner['credit2'] += $recommendMoney['money'];
                                $partner['credit5'] += $recommendMoney['redelivery'];
                                //记录订单之前各会员的奖励币余额记录
                                $res = $UserModel->where('uid', $partner['uid'])->update(['credit2' => $partner['credit2'], 'credit5' => $partner['credit5']]);
                                $this->credit2Record($order['ordersn'], $partner['uid']);
                                //重新赋值
                                $addData3['money'] = $money2;
                                $addData3['type'] = 5;
                                $addData3['text'] = '总公司一级合伙人分润';
                                $addData3['recommendMoney'] = $recommendMoney;
                                $addData3['ordersn'] = $order['ordersn'];
                                if ($res) {
                                    $this->addOrder($partner['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
                                }
                            }
                        }
                    }
                }

                //总公司二级合伙人分红
                if ($Poundage['is_two'] > 0) {
                    if ($ser_count > 0) {
                        foreach ($service as $k => $v) {
                            $ser = Members::where('name', $v['name'])->first();
                            $money3 = RETAIN_TWO($bonus_points * $Poundage['is_two'] / 100 / $ser_count);
                            $recommendMoney = CALCULATE($Poundage, $money3, 2);
                            //添加记录
                            if ($ser['type'] == 1) {
                                $ser['credit2'] += $recommendMoney['money'];
                                $ser['credit5'] += $recommendMoney['redelivery'];
                                //记录订单之前各会员的奖励币余额记录
                                $res = $UserModel->where('uid', $ser['uid'])->update(['credit2' => $ser['credit2'], 'credit5' => $ser['credit5']]);
                                $this->credit2Record($order['ordersn'], $ser['uid']);
                                //重新赋值
                                $addData4['money'] = $money3;
                                $addData4['type'] = 5;
                                $addData4['text'] = '总公司二级合伙人分润';
                                $addData4['recommendMoney'] = $recommendMoney;
                                $addData4['ordersn'] = $order['ordersn'];
                                if ($res) {
                                    $this->addOrder($ser['uid'], $addData4['money'], 5, $addData4['text'], $addData4['recommendMoney'], 0, $addData4['ordersn']);
                                }
                            }
                        }
                    }
                }
                //总公司三级合伙人分红
                if ($Poundage['is_three'] > 0) {
                    if ($ceo_count > 0) {
                        foreach ($ceo as $k => $v) {
                            $user = Members::where('name', $v['name'])->first();
                            $money4 = RETAIN_TWO($bonus_points * $Poundage['is_three'] / 100 / $ceo_count);
                            $recommendMoney = CALCULATE($Poundage, $money4, 2);
                            //添加记录
                            if ($user['type'] == 1) {
                                $user['credit2'] += $recommendMoney['money'];
                                $user['credit5'] += $recommendMoney['redelivery'];
                                //记录订单之前各会员的奖励币余额记录
                                $res = $UserModel->where('uid', $user['uid'])->update(['credit2' => $user['credit2'], 'credit5' => $user['credit5']]);
                                $this->credit2Record($order['ordersn'], $user['uid']);
                                //重新赋值
                                $addData5['money'] = $money4;
                                $addData5['type'] = 5;
                                $addData5['text'] = '总公司三级合伙人分润';
                                $addData5['recommendMoney'] = $recommendMoney;
                                $addData5['ordersn'] = $order['ordersn'];
                                if ($res) {
                                    $this->addOrder($user['uid'], $addData5['money'], 5, $addData5['text'], $addData5['recommendMoney'], 0, $addData5['ordersn']);
                                }
                            }
                        }
                    }
                }


            }
//            全国门店加权分润
            $stores = StoresCenter::where('type', 1)->get()->toArray();
            if (!empty($stores)) {
                $storeCount = count($stores);
                $storeMoney = RETAIN_TWO($bonus_points * $Poundage['store_platform'] / 100 / $storeCount);
                foreach ($stores as $k => $v) {
                    $storeMember = Members::where('uid', $v['uid'])->select('credit1', 'credit2', 'credit3', 'credit4', 'credit5')->first();
                    $recommendMoney = CALCULATE($Poundage, $storeMoney, 2);
                    //扣除平台费和复投币
                    $storeMember['credit2'] += $recommendMoney['money'];
                    $storeMember['credit5'] += $recommendMoney['redelivery'];
                    //添加记录
                    $this->addOrder($v['uid'], $storeMoney, 5, '全国服务中心分润', $recommendMoney, 0, $order['ordersn']);
                    //更新会员数据
                    $UserModel->where(['uid' => $v['uid']])->update($storeMember['attributes']);
                }
            }
            //计算门店中心收益
            if (!empty($userNumber)) {
                $storeUid = StoresCenter::where('number', $userNumber)->value('uid');
                //增加一条终身绑定门店个人账户奖励币增加的记录
                $firstUidTransactionData = [
                    'uid' => $storeUid,
                    'ordersn' => $order['ordersn'],
                    'money' => RETAIN_TWO($bonus_points * $Poundage['bind_store'] / 100),
                    'type' => 5,
                    'time' => time(),
                    'explain' => '复销商城',
                    'remark' => '终生绑定门店收益'
                ];
                $StoreFirstTransaction = $RecordTransaction->add_transaction($firstUidTransactionData);
                if (!$StoreFirstTransaction) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '终身绑定门店个人账户奖励币记录增加失败！'];
                }

                $firstSource = "姓名为" . $user["user_name"] . "，电话号码为" . $user["phone"] . "的用户在复销商城购买了共" . $money . "元的商品";

                $firstSourceStore = "姓名为" . $user["user_name"] . "，电话号码为" . substr_replace($user["phone"], '****', 3, 4) . "的用户在复销商城购买了共" . $money . "元的商品";

                $firstStoreCurrency = RETAIN_TWO($bonus_points * $Poundage['store'] / 100);

                $firstStoreNumber = $userNumber;

                //插入一条终身绑定门店返币收益记录
                $firstStoreProfitRecord = $StoresProfitRecordModel->add(['store_number' => $firstStoreNumber, 'currency' => $firstStoreCurrency, 'source' => $firstSource, 'source_store' => $firstSourceStore, 'addtime' => time(), 'profit_type' => 1, 'consum_type' => 1, 'ordersn' => $order['ordersn']]);
                if (!$firstStoreProfitRecord) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '终身绑定门店收益记录添加失败！'];
                }
            }
            //减少用户消费门店的对应商品的库存
            if ($storeNumber != '0') {
                //门店收益
                $this->StoresCenter($money, $Poundage, $order['ordersn'], $storeNumber);
                foreach ($orderComment as $k => $v) {
                    if ($v['number'] != '0') {
                        $storeGoodsNumber = StoresCenterGoods::where(['gid' => $v['goodsid'], 'stores_sn' => $userNumber])
                            ->select('goodsname', 'inventory', 'specs_txt')
                            ->first();
                        if ($storeGoodsNumber["inventory"] <= 0 || $storeGoodsNumber["inventory"] < $v['number']) {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '该门店商品:' . $storeGoodsNumber["goodsname"] . '库存不足,请提醒商家加货!'];
                            exit;
                        }
                        //减少该门店对应商品的现库存量
                        $StoreInventoryDel = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->decrement('inventory', $v['number']);
                        //增加该门店对应商品的已出售量
                        $StoreSoldAdd = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->increment('sold', $v['number']);
                        //增加门店可补货金额
                        $StoreInvoiceAdd = StoresCenter::where(['number' => $storeNumber])->increment('invoices', $money);
                        if (!$StoreInventoryDel || !$StoreSoldAdd || !$StoreInvoiceAdd) {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '门店商品库存变更失败！'];
                            exit;
                        }
                    }
                }
            }

            DB::commit();  //提交
            Session::forget('orderPay' . $id);
            Session::save();
            return ['code' => 1, 'data' => '支付成功'];
        } else {
            return ['code' => 0, 'data' => '余额不足'];
        }
    }

    /**
     * 微商城奖金计算
     * @param null $uid 会员id
     * @param null $referrer 分享人
     * @param array $micro 微商城设置
     * @param array $Poundage 系统设置
     * @param null $money 金额
     * @param int $company_id 分公司id
     * @param string $upgrade 等级
     * @param string $ordersn 统一订单
     */
    public function bonusThrow($uid = null, $referrer = null, $micro = array(), $Poundage = array(), $money = null, $company_id = 0, $ordersn = '', $bonus_points)
    {
        //会员表
        $puid = $uid;
        $userApply = new Apply();
        $user = session('home_user');
        $order = ShopOrder::where('ordersn', $ordersn)->first();
        $address = Address::where('id', $order['addressid'])->first();
        //查询该区域代理
        $userArea = $userApply->where(['type' => 2, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyArea = 0;
        if (!empty($userArea)) {
            foreach ($userArea as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyArea = $v['uid'];
                    }
                }
            }
        }
        //查询市代理
        $city = $address['city'] . $address['district'];
        $cityData = $userApply->where(['type' => 1, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyCity = 0;//市代理uid
        if (!empty($cityData)) {
            foreach ($cityData as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyCity = $v['uid'];
                    }
                }
            }
        }
        $share = $referrer;//分享人ID
        //业绩设置
        $QualityModel = new SetQuality();
        $Quality = $QualityModel->get()->toArray();
        $referrer = $referrer; //分享人
        $UserModel = new Members();
        $till = 0;
        $money1 = $money;
        $money2 = $money;
        $number1 = 1;
        $number2 = 1;
//            升等级
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->where('id', 1)->first();
//        //特价专区设置
//        $directModel = new MicroMall();
//        $direct = $directModel->where('id',1)->first();
        //特价专区设置
        $SetBonusModel = new SetBonus();
        $setBonus = $SetBonusModel->get()->toArray();

        //直推人数查询
        $number1 = 1;
        $members = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();
        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {
//                    //寻找上级id 微客
                    $referrer = $v['referrer'];
                    $arrays[$v['uid']] = $v['referrer'];
                    $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, $money);
                    //直推奖励
                    if ($ExceedShop['vip'] > 0) {
                        if ($v['super_level'] >= 1) {
                            if ($number1 == 1) {
                                $money1 = RETAIN_TWO($bonus_points * ($ExceedShop['vip'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money1, 1);
                                $number1++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $order['ordersn']);
                                    $this->addOrder($v['uid'], $money1, 5, '复投商城直推奖', $recommendMoney, $company_id, $order['ordersn']);
                                }
                            }
                        }
                    }
                }
                //更新会员数据
                $UserModel->where(['uid' => $v['uid']])->update($v);
            }
        }
        $this->bonusAgency($agencyCity, $bonus_points, $Poundage, $ordersn, $city);
        return true;
    }

    /**
     * 微商城奖金计算
     * @param null $uid 会员id
     * @param null $referrer 分享人
     * @param array $micro 微商城设置
     * @param array $Poundage 系统设置
     * @param null $money 金额
     * @param int $company_id 分公司id
     * @param string $upgrade 等级
     * @param string $ordersn 统一订单
     */
    public function bonusMicro($uid = null, $referrer = null, $micro = array(), $Poundage = array(), $money = null, $company_id = 0, $ordersn = '', $bonus_points)
    {
        //会员表
        $puid = $uid;
        $userApply = new Apply();
        $user = session('home_user');
        $order = ShopOrder::where('ordersn', $ordersn)->first();
        $address = Address::where('id', $order['addressid'])->first();
        //查询该区域代理
        $userArea = $userApply->where(['type' => 2, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyArea = 0;
        if (!empty($userArea)) {
            foreach ($userArea as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyArea = $v['uid'];
                    }
                }
            }
        }
        //查询市代理
        $city = $address['city'] . $address['district'];
        $cityData = $userApply->where(['type' => 1, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyCity = 0;//市代理uid
        if (!empty($cityData)) {
            foreach ($cityData as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyCity = $v['uid'];
                    }
                }
            }
        }
        $share = $referrer;//分享人ID
        //业绩设置
        $QualityModel = new SetQuality();
        $Quality = $QualityModel->get()->toArray();
        $referrer = $referrer; //分享人
        $UserModel = new Members();
        $till = 0;
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $money6 = $money;
        $money7 = $money;
        $money8 = $money;
        $money9 = $money;
        $money10 = $money;
        $money11 = $money;
        $money12 = $money;
        $money13 = $money;
        $money14 = $money;
        $number3 = 1;
        $number4 = 1;
        $number5 = 1;
        $number6 = 1;
        $number7 = 1;
        $number8 = 1;
        $number9 = 1;
        $number10 = 1;
        $number11 = 1;
        $number12 = 1;
        $number13 = 1;
        $number14 = 1;
//            升等级
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->get()->toArray();
        //特价专区设置
        $directModel = new MicroMall();
        $direct = $directModel->where('id', 1)->first();
        //特价专区设置
        $SetBonusModel = new SetBonus();
        $setBonus = $SetBonusModel->get()->toArray();
        //直推人数查询
        $number1 = 1;
        $users = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();
        foreach ($users as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {
//                    //寻找上级id 微客
                    $referrer = $v['referrer'];
                    $arrays[$v['uid']] = $v['referrer'];
                    $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, $money);
                    //直推奖励
                    if ($direct['direct'] > 0) {
                        if ($v['super_level'] >= 1) {
                            if ($number1 == 1) {
                                $money1 = RETAIN_TWO($bonus_points * ($direct['direct'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money1, 1);
                                $number1++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $order['ordersn']);
                                    $this->addOrder($v['uid'], $money1, 5, '复销商城直推奖', $recommendMoney, $company_id, $order['ordersn']);
                                }

                            }
                        }
                    }
                    if ($bonus_points > 0) {
                        //V1 一阶段奖励
                        if (($v['level'] == 1 && $v['level_grade'] >= 1) || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 1])->first();
                            if ($number3 <= 2) {
                                if ($number3 == 1) {
                                    $money3 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                    $number3++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money3, 5, 'V1业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money3 = RETAIN_TWO($money3 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                        $number3++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money3, 5, 'V1业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }
                        }
                        //V1 二阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 2 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 2])->first();
                            if ($number4 <= 2) {
                                if ($number4 == 1) {
                                    $money4 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                    $number4++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money4, 5, 'V1业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money4 = RETAIN_TWO($money4 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                        $number4++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money4, 5, 'V1业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }
                                }
                            }

                        }
                        //V1 三阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 3 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 3])->first();
                            if ($number5 <= 2) {
                                if ($number5 == 1) {
                                    $money5 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                    $number5++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money5, 5, 'V1业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money5 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                        $number5++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money5, 5, 'V1业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 四阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 4 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 4])->first();
                            if ($number8 <= 2) {
                                if ($number8 == 1) {
                                    $money8 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                    $number8++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money8, 5, 'V1业绩分享奖(四阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money8 = RETAIN_TWO($money8 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                        $number8++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money8, 5, 'V1业绩管理奖(四阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 五阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 5 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 5])->first();
                            if ($number13 <= 2) {
                                if ($number13 == 1) {
                                    $money13 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money13, 1);
                                    $number13++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money13, 5, 'V1业绩分享奖(五阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money13 = RETAIN_TWO($money13 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money13, 1);
                                        $number13++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money13, 5, 'V1业绩管理奖(五阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 六阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 6 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 6])->first();
                            if ($number14 <= 2) {
                                if ($number14 == 1) {
                                    $money14 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money14, 1);
                                    $number14++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money14, 5, 'V1业绩分享奖(六阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money14 = RETAIN_TWO($money14 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money14, 1);
                                        $number14++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money14, 5, 'V1业绩管理奖(六阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V2 一阶段奖励
                        if ($v['level'] == 2 && $v['level_grade'] >= 1 || $v['level'] > 2) {
                            $set = SetQuality::where(['level' => 2, 'level_stage' => 1])->first();
                            if ($number6 <= 2) {
                                if ($number6 == 1) {
                                    $money6 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                    $number6++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money6, 5, 'V2业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money6 = RETAIN_TWO($money6 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                    $number6++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money6, 5, 'V2业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        //V2 二阶段奖励
                        if ($v['level'] == 2 && $v['level_grade'] >= 2 || $v['level'] > 2) {
                            $set = SetQuality::where(['level' => 2, 'level_stage' => 2])->first();
                            if ($number7 <= 2) {
                                if ($number7 == 1) {
                                    $money7 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                    $number7++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money7, 5, 'V2业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money7 = RETAIN_TWO($money7 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                    $number7++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money7, 5, 'V2业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        //V2 三阶段奖励
                        if ($v['level'] == 2 && $v['level_grade'] >= 3 || $v['level'] > 2) {
                            $set = SetQuality::where(['level' => 2, 'level_stage' => 3])->first();
                            if ($number9 <= 2) {
                                if ($number9 == 1) {
                                    $money9 = RETAIN_TWO($bonus_points * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money9, 5, 'V2业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money9 = RETAIN_TWO($money9 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money9, 5, 'V3业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                    }

                }
                //更新会员数据
                $UserModel->where(['uid' => $v['uid']])->update($v);
            }
        }
        $this->bonusAgency($agencyCity, $bonus_points, $Poundage, $ordersn, $city);
        return true;
    }

    /**
     * 门店中心奖励
     * @param $money 金额
     * @param $company_id 分公司id
     * @param $Poundage 系统设置
     * @param $ordersn 订单号
     * @param $StoresNumber 门店中心 [uid,number]
     * @return array
     */
    public function StoresCenter($money, $Poundage, $ordersn, $StoresNumber)
    {
        if ($money < 0 || empty($money)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //计算金额
        $recommend = RETAIN_TWO($money * $Poundage['store'] / 100);
        //会员表
        $UserModel = new Members();
        $storeUid = StoresCenter::where('number', $StoresNumber)->value('uid');
        //查询门店
        $member = $UserModel->where(['uid' => $storeUid])->select('uid', 'credit2')->first();
        if ($member) {
            //扣除平台费和复投币
            $recommendMoney['money'] = $recommend;
            $recommendMoney['redelivery'] = 0;
            $recommendMoney['platform_fee'] = 0;
            $member['credit2'] += $recommendMoney['money'];
            //添加记录
            $this->addOrder($member['uid'], $recommend, 5, '消费门店收益', $recommendMoney, 0, $ordersn);
            //更新会员数据
            $UserModel->where(['uid' => $member['uid']])->update($member['attributes']);

        }
    }

    /**
     * * 报单商城奖金计算
     * @param null $uid
     * @param null $referrer
     * @param array $ExceedShop
     * @param array $Quality
     * @param int $grade_type
     * @param array $Poundage
     * @param null $money
     * @param string $ordersn
     * @param int $type
     * @return bool
     */
    public function superShop($uid = null, $referrer = null, $Quality = array(), $grade_type = 1, $Poundage = array(), $points = null, $ordersn = '', $money = null, $setBonus = array())
    {
        //会员表
        $type = 0;
        $company_id = 0;
        $UserModel = new Members();
        $userApply = new Apply();
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->where(['id' => 1])->first();
        $order = ShopOrder::where('ordersn', $ordersn)->first();
        $address = Address::where('id', $order['addressid'])->first();
        //查询该区域代理
        //查询市代理
        $cityData = $userApply->where(['type' => 1, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyCity = 0;//市代理uid
        if (!empty($cityData)) {
            foreach ($cityData as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyCity = $v['uid'];
                    }
                }
            }
        }
        $city = $address['city'] . $address['district'];
        $bonusLevel = 0;//奖励等级
        $share = $referrer;//分享人ID
        $puid = $uid;
//        $achive = ShopOrder::where('ordersn',$ordersn)->value('price');
        $money1 = $money;
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $money6 = $money;
        $money7 = $money;
        $money8 = $money;
        $money9 = $money;
        $money10 = $money;
        $money11 = $money;
        $money12 = $money;
        $money13 = $money;
        $money14 = $money;
        $number1 = 1;
        $number3 = 1;
        $number4 = 1;
        $number5 = 1;
        $number6 = 1;
        $number7 = 1;
        $number8 = 1;
        $number9 = 1;
        $number10 = 1;
        $number11 = 1;
        $number12 = 1;
        $number13 = 1;
        $number14 = 1;
        $ricos = 1; //判断错误
        $arrays = [];
        $members = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();

        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {    //寻找上级id 微客
                    $referrer = $v['referrer'];
                    //会员等级升级
                    $arrays[$v['uid']] = $v['referrer'];
                    $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, $points);
                    //直推奖励
                    if ($ExceedShop['vip'] > 0 && $money > 0) {
                        if ($v['super_level'] >= 1) {
                            if ($number1 == 1) {
                                $money1 = RETAIN_TWO($money * ($ExceedShop['vip'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money1, 1);
                                $number1++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $order['ordersn']);
                                    $this->addOrder($v['uid'], $money1, 5, '报单直推奖', $recommendMoney, $company_id, $order['ordersn']);
                                }
                            }
                        }
                    }
                    if ($money > 0) {
                        //V1 一阶段奖励
                        if (($v['level'] == 1 && $v['level_grade'] >= 1) || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 1])->first();
                            if ($number3 <= 2) {
                                if ($number3 == 1) {
                                    $money3 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                    $number3++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money3, 5, 'V1业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money3 = RETAIN_TWO($money3 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                        $number3++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money3, 5, 'V1业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }
                        }
                        //V1 二阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 2 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 2])->first();
                            if ($number4 <= 2) {
                                if ($number4 == 1) {
                                    $money4 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                    $number4++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money4, 5, 'V1业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money4 = RETAIN_TWO($money4 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                        $number4++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money4, 5, 'V1业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }
                                }
                            }

                        }
                        //V1 三阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 3 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 3])->first();
                            if ($number5 <= 2) {
                                if ($number5 == 1) {
                                    $money5 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                    $number5++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money5, 5, 'V1业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money5 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                        $number5++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money5, 5, 'V1业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 四阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 4 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 4])->first();
                            if ($number8 <= 2) {
                                if ($number8 == 1) {
                                    $money8 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                    $number8++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money8, 5, 'V1业绩分享奖(四阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money8 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                        $number8++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money8, 5, 'V1业绩管理奖(四阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 五阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 5 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 5])->first();
                            if ($number13 <= 2) {
                                if ($number13 == 1) {
                                    $money13 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money13, 1);
                                    $number13++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money13, 5, 'V1业绩分享奖(五阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money13 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money13, 1);
                                        $number13++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money13, 5, 'V1业绩管理奖(五阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 六阶段奖励
                        if ($v['level'] == 1 && $v['level_grade'] >= 6 || $v['level'] > 1) {
                            $set = SetQuality::where(['level' => 1, 'level_stage' => 6])->first();
                            if ($number14 <= 2) {
                                if ($number14 == 1) {
                                    $money14 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money14, 1);
                                    $number14++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money14, 5, 'V1业绩分享奖(六阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money14 = RETAIN_TWO($money14 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money14, 1);
                                        $number14++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money14, 5, 'V1业绩管理奖(六阶段)', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V2 一阶段奖励
                        if ($v['level'] == 2 && $v['level_grade'] >= 1 || $v['level'] > 2) {
                            $set = SetQuality::where(['level' => 2, 'level_stage' => 1])->first();
                            if ($number6 <= 2) {
                                if ($number6 == 1) {
                                    $money6 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                    $number6++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money6, 5, 'V2业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money6 = RETAIN_TWO($money6 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                    $number6++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money6, 5, 'V2业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        //V2 二阶段奖励
                        if ($v['level'] == 2 && $v['level_grade'] >= 2 || $v['level'] > 2) {
                            $set = SetQuality::where(['level' => 2, 'level_stage' => 2])->first();
                            if ($number7 <= 2) {
                                if ($number7 == 1) {
                                    $money7 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                    $number7++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money7, 5, 'V2业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money7 = RETAIN_TWO($money7 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                    $number7++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money7, 5, 'V2业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        //V2 三阶段奖励
                        if ($v['level'] == 2 && $v['level_grade'] >= 3 || $v['level'] > 2) {
                            $set = SetQuality::where(['level' => 2, 'level_stage' => 3])->first();
                            if ($number9 <= 2) {
                                if ($number9 == 1) {
                                    $money9 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money9, 5, 'V2业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money9 = RETAIN_TWO($money9 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money9, 5, 'V3业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                    }

                    $puid = $v['uid'];
                    //更新会员数据
                    if ($UserModel->where(['uid' => $v['uid']])->update(
                        [
                            'credit1' => $v['credit1'],
                            'credit2' => $v['credit2'],
                            'credit5' => $v['credit5'],
                            'level' => $v['level'],
                            'level_name' => $v['level_name'],
                            'level_grade' => $v['level_grade'],
                            'super_recommend' => $v['super_recommend'],
                            'team_member_count' => $v['team_member_count'],
                            'super_team_count' => $v['super_team_count'],
                            'super_small_team_count' => $v['super_small_team_count'],
                            //                            'super_level' => $v['super_level'],
                            //                            'super_level_name' => $v['super_level_name'],

                        ]
                    )
                    ) {
                        //添加记录
                        if (!empty($v['addData']['addData1'])) {
                            $this->addOrder($v['uid'], $v['addData']['addData1']['money'], 5, $v['addData']['addData1']['text'], $v['addData']['addData1']['recommendMoney'], 0, $v['addData']['addData1']['ordersn']);
                        }

                    } else {

                        return false;
                    }

                }
            }
        }
//        代理奖励分配
        $this->bonusAgency($agencyCity, $money, $Poundage, $ordersn, $city);
        return true;
    }


    /**
     * 平台合伙人分红
     * @return void
     */
    public function addPlatform($ordersn, $total)
    {
        //系统设置
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        if (!empty($total)) {
            //合伙人人数
            $member_count = SetPartner::where(['status' => 1])->count();
            //每人分红金额
            $money = RETAIN_TWO($total / $member_count);
            if ($money > 0) {
                $record = [
                    'ordersn' => $ordersn,
                    'money' => $money,
                    'number' => $member_count,
                    'total_money' => $total,
                    'name' => '平台合伙人订单分红',
                    'time' => time()
                ];
                DB::beginTransaction(); //开启事务
                $res = PartnerRecord::create($record);
                if ($res) {
                    //合伙人分红
                    $members = SetPartner::where(['status' => 1])->get()->toArray();
                    foreach ($members as $k => $v) {
                        $user = Members::where('name', $v['name'])->first();
                        $recommendMoney = [
                            'money' => RETAIN_TWO($money * (100 - $Poundage['redelivery'] - $Poundage['platform_fee']) / 100),
                            'redelivery' => RETAIN_TWO($money * $Poundage['redelivery'] / 100),
                            'platform_fee' => RETAIN_TWO($money * $Poundage['platform_fee'] / 100)];
                        $re = Members::where('name', $v['name'])->update(['credit2' => $user['credit2'] + $recommendMoney['money'], 'credit5' => $user['credit5'] + $recommendMoney['redelivery']]);

                        $this->addOrder($user['uid'], $money, 5, '平台合伙人分红', $recommendMoney, 0, $ordersn);
                        if (!$re) {
                            DB::rollback();
                            return ['code' => 0, 'data' => '分红失败'];
                        }
                    }
                } else {
                    DB::rollback();
                    return ['code' => 0, 'data' => '记录添加失败'];
                }

                DB::commit();
                return ['code' => 1, 'data' => '分红成功'];
            }

        } else {
            return ['code' => 0, 'data' => '分红金额不足'];
        }
    }

    /**
     * 代理奖励分配
     * @param $agencyCity
     * @param $money
     * @param $Poundage
     * @param $ordersn
     */
    public function bonusAgency($agencyCity, $money, $Poundage, $ordersn, $city)
    {
        $money1 = $money;
        $money2 = $money;
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $UserModel = new Members();
        if (!empty($agencyCity)) {  //市代理奖励
            $apply_id = Apply::where('uid', $agencyCity)->value('id');
            $partners = SetRebate::where(['a_id' => $apply_id, 'is_partner' => 1, 'status' => 1])->get()->toArray();
            $service = SetRebate::where(['a_id' => $apply_id, 'is_service' => 1, 'status' => 1])->get()->toArray();
            $ceo = SetRebate::where(['a_id' => $apply_id, 'is_ceo' => 1, 'status' => 1])->get()->toArray();
            $investment = SetRebate::where(['a_id' => $apply_id, 'is_investor' => 1, 'status' => 1])->get()->toArray();
            $ser_count = count($service);
            $count = count($partners);
            $ceo_count = count($ceo);
            $invest_count = count($investment);
            if ($count == 0) {
                $Poundage['distribution'] = 0;
            }
            if ($ser_count == 0) {
                $Poundage['platform_profit'] = 0;
            }
            if ($ceo_count == 0) {
                $Poundage['ceo'] = 0;
            }
            if ($invest_count == 0) {
                $Poundage['investment'] = 0;
            }
            //判断比例是否大于0
            if ($Poundage['distribution'] > 0) {
                //代理合伙人分红
                if ($count > 0) {
                    foreach ($partners as $k => $v) {
                        $partner = Members::where('name', $v['name'])->first();
                        $money2 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['distribution'] / 100 / $count);
                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
                        //添加记录
                        if ($partner['type'] == 1) {
                            $partner['credit2'] += $recommendMoney['money'];
                            $partner['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $partner['uid'])->update(['credit2' => $partner['credit2'], 'credit5' => $partner['credit5']]);
                            $this->credit2Record($ordersn, $partner['uid']);
                            //重新赋值
                            $addData3['money'] = $money2;
                            $addData3['type'] = 5;
                            $addData3['text'] = $city . '合伙人分润';
                            $addData3['recommendMoney'] = $recommendMoney;
                            $addData3['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($partner['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
                            }
                        }
                    }
                }
            }
            //判断比例是否大于0
            if ($Poundage['platform_profit'] > 0) {
                //添加服务组分红
                if ($ser_count > 0) {
                    foreach ($service as $k => $v) {
                        $ser = Members::where('name', $v['name'])->first();
                        $money3 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['platform_profit'] / 100 / $ser_count);
                        $recommendMoney = CALCULATE($Poundage, $money3, 2);
                        //添加记录
                        if ($ser['type'] == 1) {
                            $ser['credit2'] += $recommendMoney['money'];
                            $ser['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $ser['uid'])->update(['credit2' => $ser['credit2'], 'credit5' => $ser['credit5']]);
                            $this->credit2Record($ordersn, $ser['uid']);
                            //重新赋值
                            $addData4['money'] = $money3;
                            $addData4['type'] = 5;
                            $addData4['text'] = $city . '运营分润';
                            $addData4['recommendMoney'] = $recommendMoney;
                            $addData4['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($ser['uid'], $addData4['money'], 5, $addData4['text'], $addData4['recommendMoney'], 0, $addData4['ordersn']);
                            }
                        }
                    }
                }
            }
            if ($Poundage['investment'] > 0) {
                //添加总务分红
                if ($invest_count > 0) {
                    foreach ($investment as $k => $v) {
                        $invest = Members::where('name', $v['name'])->first();
                        $money5 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['investment'] / 100 / $invest_count);
                        $recommendMoney = CALCULATE($Poundage, $money5, 2);
                        //添加记录
                        if ($invest['type'] == 1) {
                            $invest['credit2'] += $recommendMoney['money'];
                            $invest['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $invest['uid'])->update(['credit2' => $invest['credit2'], 'credit5' => $invest['credit5']]);
                            $this->credit2Record($ordersn, $invest['uid']);
                            //重新赋值
                            $addData6['money'] = $money5;
                            $addData6['type'] = 5;
                            $addData6['text'] = $city . '总务分润';
                            $addData6['recommendMoney'] = $recommendMoney;
                            $addData6['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($invest['uid'], $addData6['money'], 5, $addData6['text'], $addData6['recommendMoney'], 0, $addData6['ordersn']);
                            }
                        }
                    }
                }
            }

            //添加区域CEO分红
            if ($Poundage['ceo'] > 0) {
                if ($ceo_count > 0) {
                    foreach ($ceo as $k => $v) {
                        $user = Members::where('name', $v['name'])->first();
                        $money4 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['ceo'] / 100 / $ceo_count);
                        $recommendMoney = CALCULATE($Poundage, $money4, 2);
                        //添加记录
                        if ($user['type'] == 1) {
                            $user['credit2'] += $recommendMoney['money'];
                            $user['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $user['uid'])->update(['credit2' => $user['credit2'], 'credit5' => $user['credit5']]);
                            $this->credit2Record($ordersn, $user['uid']);
                            //重新赋值
                            $addData5['money'] = $money4;
                            $addData5['type'] = 5;
                            $addData5['text'] = $city . '区域CEO分润';
                            $addData5['recommendMoney'] = $recommendMoney;
                            $addData5['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($user['uid'], $addData5['money'], 5, $addData5['text'], $addData5['recommendMoney'], 0, $addData5['ordersn']);
                            }
                        }
                    }
                }
            }


        }

    }


    /**
     * 报单商城升级处理
     * @param $v 会员数据
     * @param $puid 上级会员
     * @param $ExceedShop 超级商城设置
     * @param $Quality 商城业绩设置
     * @return mixed 返回会员数据
     */

    public function UpGrade($v, $puid, $Quality, $array = array(), $share, $points)
    {
        $v['super_team_count'] += $points;
        $v['team_member_count'] += 1;
        //添加小区团队
        $super_small_team_count = json_decode($v['super_small_team_count'], true);
        if ($super_small_team_count) {  //判断是否已有团队业绩
            foreach ($super_small_team_count as $items => $item) {
                if ($share == $v['uid']) {//判断是否已有这个会员的业绩
                    $super_small_team_count[$puid] = [
                        'key' => $puid,
                        'val' => 1,
                        'money' => $points,
                    ];

                }
                if (isset($array[$items]) ? $array[$items] : 0) {
                    $super_small_team_count[$items]['money'] += $points;
                    $super_small_team_count[$items]['val'] += 1;
                }
            }
            $super_small_team_count = json_encode($super_small_team_count);

        } else {
            $team_count = [
                $puid => [
                    'key' => $puid,
                    'val' => 1,
                    'money' => $points,
                ]
            ];

            $super_small_team_count = json_encode($team_count);
        }
        $v['super_small_team_count'] = $super_small_team_count; //添加小区团队
        /*--------------------------------------**/
        //直推人数查询
        $realTeamCount = Members::where(['referrer' => $v['uid']])->select('uid')->count();
        $v['super_recommend'] = $realTeamCount;
        if ($v['level'] == 0) {  //v1
            if ($v['super_team_count'] >= $Quality[0]['team_count']) {
                $v['level_name'] = $Quality[0]['level_name'];
                $v['level'] = $Quality[0]['level'];
                $v['level_grade'] = $Quality[0]['level_stage'];
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[1]['team_count']) {
                    $v['level_grade'] = $Quality[1]['level_stage'];
                }
            }

        }

        if ($v['level'] == 1 && $v['level_grade'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[2]['team_count'] ) {
                    $v['level_grade'] = $Quality[2]['level_stage'];
                }
            }

        }

        if ($v['level'] == 1 && $v['level_grade'] == 3) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[3]['team_count']) {
                    $v['level_grade'] = $Quality[3]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 4) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[4]['team_count']) {
                    $v['level_name'] = $Quality[4]['level_name'];
                    $v['level'] = $Quality[4]['level'];
                    $v['level_grade'] = $Quality[4]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 5) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[5]['team_count']) {
                    $v['level_name'] = $Quality[5]['level_name'];
                    $v['level'] = $Quality[5]['level'];
                    $v['level_grade'] = $Quality[5]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 6) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[6]['team_count'] ) {
                    $v['level_name'] = $Quality[6]['level_name'];
                    $v['level'] = $Quality[6]['level'];
                    $v['level_grade'] = $Quality[6]['level_stage'];
                }
            }
        }

        if ($v['level'] == 2 && $v['level_grade'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($counts >= $Quality[7]['small_team_count'] ) {
                    $v['level_grade'] = $Quality[7]['level_stage'];
                }
            }
        }

        if ($v['level'] == 2 && $v['level_grade'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($counts >= $Quality[8]['small_team_count']) {
                    $v['level_name'] = $Quality[8]['level_name'];
                    $v['level'] = $Quality[8]['level'];
                    $v['level_grade'] = $Quality[8]['level_stage'];
                }
            }
        }
        return $v;
    }


    /**
     * 个人资料
     */
    public function myUser()
    {
        return view('Home.member.myuser');
    }

    /**
     * 我的二维码
     */
    public function myQrCode()
    {
        return view('Home.member.myqrcode');
    }

    /**
     * 我的二维码
     */
    public function myOreder()
    {
        return view('Home.member.myoreder');
    }

    public function sign()
    {
        return view('Home.member.sign');
    }

    /**
     * 我的购物车
     */
    public function shopCart()
    {
        return view('Home.member.shopcart');
    }

    /**
     * 添加我的收货地址
     */
    public function address()
    {
        return view('Home.member.address');
    }

    /**
     * 添加我的收货地址
     */
    public function addressList()
    {
        return view('Home.member.addresslist');
    }

    /**
     * 我的注册资料
     */
    public function userInfo()
    {
        return view('Home.member.userInfo');
    }

    /**
     * 修改登陆密码
     */
    public function loginPass()
    {
        return view('Home.member.loginPass');
    }

    /**
     * 修改支付密码
     */
    public function payPass()
    {
        return view('Home.member.paypPass');
    }

    /**
     * 代理申请
     */
    public function apply()
    {
        return view('Home.member.apply');
    }

    /**
     * 财务列表
     */
    public function finance()
    {
        return view('Home.member.finance');
    }

    /**
     * 财务管理详情
     */
    public function financeDetail()
    {
        return view('Home.member.financeDetail');
    }


    /**
     * 添加我的收货地址
     */
    public function AddAddress(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        $data['address']['uid'] = $user->uid;
        switch ($data['class']) {
            case 'select': //查询
                $rico = Address::orderBy('default', 'decs')->where(['uid' => $user->uid])->get()->toArray();
                if ($rico) {
                    return ['code' => 1, 'data' => $rico];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'add':    //添加 or 修改
                $default = Address::where('uid', $data['address']['uid'])->first();
                if ($default) {
                    if ($data['address']['default']) {
                        Address::where('uid', $data['address']['uid'])->update(['default' => 0]);
                    }
                }
                if ($data['address']['id']) { //修改
                    $rico = Address::where('id', $data['address']['id'])->update($data['address']);
                } else {
                    $rico = Address::create($data['address']);
                }
                if ($rico) {
                    return ['code' => 1, 'data' => '设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'find':   //查询一条数据
                if (!empty($data['id'])) {
                    $goods = Address::where('id', $data['id'])->first();
                } else {
                    $goods = Address::where(['uid' => $user->uid, 'default' => 1])->first();
                    if (!$goods) {
                        $goods = Address::where('uid', $user['uid'])->first();
                    }
                }
                if (isset($data['addressId'])) {
                    $goods = Address::where('id', $data['addressId'])->first();
                }
                if ($goods) {
                    return ['code' => 1, 'data' => $goods];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'delete': //删除
                if ($data['id']) {
                    $defaultValue = Address::where('id', $data['id'])->value('default');
                    if (!$defaultValue) {
                        $rico = Address::where('id', $data['id'])->delete();
                    } else {
                        return ['code' => 0, 'data' => '不能删除默认地址!'];
                    }
                    if ($rico) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                } else {
                    return ['code' => 0, 'data' => '数据错误'];
                }
                break;
        }
    }

    /**
     * 我的订单
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function myOrder(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
        $uid = $user->uid;
        $orderModel = new ShopOrder();
        $UserModel = new Members();
        $StoresCenterModel = new StoresCenter();
        switch ($data['class']) {
            case 'select': //查询
                if (empty($data['status'])) {
                    $users = $orderModel->where(['uid' => $uid])
                        ->where('status', '>', 0)
                        ->orderBy('id', 'desc')->paginate(5);
                } else if (!empty($data['status']) && $data['status'] == 1) {
                    $users = $orderModel->where(['uid' => $uid])
                        ->where('status', '=', 1)
                        ->orderBy('id', 'desc')
                        ->paginate(5);
                } else if (!empty($data['status']) && $data['status'] == 2) {
                    $users = $orderModel->where(['uid' => $uid])
                        ->where('status', '=', 2)
                        ->orderBy('id', 'desc')
                        ->paginate(5);
                } else {
                    $users = $orderModel->where(['uid' => $uid])
                        ->where('status', '=', 3)
                        ->orderBy('id', 'desc')
                        ->paginate(5);
                }
                foreach ($users as $k => $v) {
                    $order_goods = ShopOrderComment::join('shop_goods', 'shop_goods.id', '=', 'shop_order_comment.goodsid')
                        ->select('shop_goods.goodsname',
                            'shop_goods.goods_thumb',
                            'shop_goods.id',
                            'shop_order_comment.goodsid'
                        )
                        ->where('orderid', $v['id'])
                        ->first();
                    $users[$k]['goodsname'] = $order_goods['goodsname'];
                    $users[$k]['goods_thumb'] = $order_goods['goods_thumb'];
                }

                if ($users) {
                    return ['code' => 1, 'data' => $users];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'select_stores_order': //门店订单查询
                $stores_number = $StoresCenterModel->where(['uid' => $user->uid])->value("number");
                $users = $orderModel->where(['stores_number' => $stores_number])->select('id', 'uid', 'ordersn', 'price', 'freight', 'status', 'createtime', 'ordertype')->orderBy('id', 'desc')->paginate(5);
                foreach ($users as $k => $v) {
                    $users[$k]["user_name"] = $UserModel->where(['uid' => $v['uid']])->value('user_name');
                }
                if ($users) {
                    return ['code' => 1, 'data' => $users];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'add':    //添加 or 修改
                $default = Address::where('uid', $data['address']['uid'])->first();
                if ($default) {
                    if ($data['address']['default']) {
                        Address::where('uid', $data['address']['uid'])->update(['default' => 0]);
                    }
                }
                if ($data['address']['id']) { //修改
                    $rico = Address::where('id', $data['address']['id'])->update($data['address']);
                } else {
                    $rico = Address::create($data['address']);
                }
                if ($rico) {
                    return ['code' => 1, 'data' => '设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'find':   //查询一条数据
                $goods = Address::where('id', $data['id'])->first();
                if ($goods) {
                    return ['code' => 1, 'data' => $goods];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'affirms'://确认收货
                $order = ShopOrder::where('id', $data['id'])->first();
                if ($order['status'] != 2) {
                    return ['code' => 0, 'data' => '还未发货'];
                }
                $data['status'] = 3;
                $res = ShopOrder::where('id', $data['id'])->update(array_only($data, ['status']));
                if ($res) {
                    return ['code' => 1, 'data' => '收货成功'];
                } else {
                    return ['code' => 0, 'data' => '收货失败'];
                }
                break;
            case 'delete': //删除
                if ($data['id']) {
                    $rico = Address::where('id', $data['id'])->delete();
                    if ($rico) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                } else {
                    return ['code' => 0, 'data' => '数据错误'];
                }
                break;
        }
    }

    /**
     * 我的购物车
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function myCart(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
        $uid = $user->uid;
        $ShopMemberCart = new ShopMemberCart();
        $ShopGoods = new ShopGoods();
        switch ($data['class']) {
            case 'select': //查询
                $carts = $ShopMemberCart->get_cart($uid);
                if (empty($carts)) {
                    return ['code' => 0, 'data' => '没有商品'];
                }
                $total = 0;        //商品总件数
                $totalNumber = 0;  //商品总数量
                $totalPrice = 0;   //总价格
                foreach ($carts as $k => $value) {
                    $goods = $ShopGoods->find_shop($value['goodsid']);
                    $carts[$k]['purchase_num'] = $goods['purchase_num'];
                    $carts[$k]['total'] = $goods->total;
//                    $img = ShopGoodsImg::where(['gid' => $value['goodsid']])->select('img')->first();
                    $carts[$k]['img'] = $goods['goods_thumb'];
                    $total += 1; //商品种类数量
                    $totalNumber += $value['number']; //商品数量
                    $totalPrice += ($value['number'] * $value['rulingprice']); //商品数量
                }
                $data = [
                    'data' => $carts,
                    'total' => $total,
                    'totalNumber' => $totalNumber,
                    'totalPrice' => $totalPrice,
                ];

                if ($carts) {
                    return ['code' => 1, 'data' => $data];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;

            case 'delete':
                if (empty($data['id'])) {
                    return ['code' => 0, 'data' => '数据错误'];
                }
                $rico = $ShopMemberCart->where(['id' => $data['id']])->delete();
                if ($rico) {
                    return ['code' => 1, 'data' => '操作成功'];
                } else {
                    return ['code' => 0, 'data' => '操作失败'];
                }
                break;
        }
    }

    /**
     * 转账
     */
    public function transfer()
    {
        return view('Home.member.transfer');
    }

    /**
     * 转账
     */
    public function deposit(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
        $uid = $user->uid;
        //会员表
        $MemberModel = new Members();
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //转账记录表
        $RecordTransferAccounts = new RecordTransferAccounts();
        switch ($data['class']) {
            case 'select': //查询
                $rico = $RecordTransferAccounts->get_transfer(['uid' => $uid], 50);
                foreach ($rico as $k => $value) {
                    $rico[$k]['time'] = date('Y-m-d H:i', $value['time']);
                    $rico[$k]['user_name'] = empty($value['user_name']) ? "暂无记录" : $value['user_name'];
                }
                if ($rico) {
                    return ['code' => 1, 'data' => $rico];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;

            case 'add': //查询
                $money = intval($data['user']['money']);
                $type = intval($data['user']['type']);
                if (empty($type)) {
                    return ['code' => 0, 'data' => '请选择转账类型'];
                }
                if (empty($money)) {
                    return ['code' => 0, 'data' => '请输入转账金额'];
                }
//                if ($money % 100 != 0) {
//                    //是100的整数
//                    return ['code' => 0, 'data' => '请输入100的倍数'];
//                }
                if ($type > 3 || $type < 1 || empty($type)) {
                    return ['code' => 0, 'data' => '请选择正确的转账方式'];
                }
                $recipient = $MemberModel->find_members(['name' => $data['user']['phone']]);
                if (empty($recipient) || $recipient['uid'] == $uid) {
                    return ['code' => 0, 'data' => '没有对方数据'];
                }
                $user = $MemberModel->find_members(['uid' => $uid]);
                if (ENCRYPTION($data['user']['password'], $user['salting_pay']) != $user['password_pay']) {
                    return ['code' => 0, 'data' => '支付密码错误！'];
                }
                if ($user['is_shift'] != 1) {
                    return ['code' => 0, 'data' => '暂未开启！'];
                }
//                if (empty($data['user']['name'])) {
//                    return ['code' => 0, 'data' => '验证码不能为空！'];
//                }
//                $phone = $user['phone'];
//                $rand = Session::get('registers_code' . $phone)['rand'];
//
//                if ($rand != intval($data['user']['name'])) {
//                    return ['code' => 0, 'data' => '验证码不正确！'];
//                }
                if ($type == 1) { //电子币
                    $credit = '电子积分';
                    $creditNnem = 'credit1';
                } elseif ($type == 2) { //奖励币
                    $credit = '奖励积分';
                    $creditNnem = 'credit2';
                } elseif ($type == 3) {//阅读积分
                    $credit = '阅读积分';
                    $creditNnem = 'credit4';
                }
                $userCreditOld = $user[$creditNnem];//转出人(支付方)
                $userCreditOldCome = $recipient[$creditNnem];//转入人
                if ($user[$creditNnem] < $money) {
                    return ['code' => 0, 'data' => '金额超出了您承受的范围！'];
                }
                DB::beginTransaction(); //开启事务
                //减
                $comeSub = bcsub($userCreditOld, $money, 2);
                //转出人
                $come = $MemberModel->where(['uid' => $user['uid']])->update([$creditNnem => $comeSub]);
                //加
                $enterAdd = bcadd($userCreditOldCome, $money, 2);
                //转进人
                $enter = $MemberModel->where(['uid' => $recipient['uid']])->update([$creditNnem => $enterAdd]);
                if (!$enter || !$come) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '转账失败'];
                }
                //查询修改后的用户余额
                $expend = Members::where('uid', $user['uid'])->value($creditNnem);
                $income = Members::where('uid', $recipient['uid'])->value($creditNnem);
                if (bcsub($expend, $comeSub) == '0' && bcsub($income, $enterAdd) == '0') {
                    $ordersn = ORDER_SN();
                    $Transaction0 = [
                        'uid' => $uid,
                        'ordersn' => $ordersn,
                        'money' => -$money,
                        'type' => 2, //1 订单 2 转账 3 提现
                        'time' => time(),
                        'explain' => $credit . '转给' . $recipient['user_name'],
                        'remark' => '支出之前,该用户' . $credit . '余额为:' . $userCreditOld
                    ];
                    $Transaction1 = [
                        'uid' => $recipient['uid'],
                        'ordersn' => $ordersn,
                        'money' => $money,
                        'type' => 2, //1 订单 2 转账 3 提现
                        'time' => time(),
                        'explain' => $user['user_name'] . '转入' . $credit,
                        'remark' => '收入之前,该用户' . $credit . '余额为:' . $userCreditOldCome
                    ];
                    $enterId = $RecordTransaction->add_transaction($Transaction0);
                    $comeId = $RecordTransaction->add_transaction($Transaction1);
                    if ($enterId && $comeId) {
                        //添加转进人记录
                        $enterData = [
                            'uid' => $recipient['uid'],
                            'tid' => $comeId,
                            'type' => $type,
                            'money' => $money,
                            'transfer' => $user['uid'],
                            'user_name' => $user['user_name'],
                            'nickname' => $recipient['user_name'],
                            'remark' => $credit . ':收入之前,该用户' . $credit . '余额为:' . $userCreditOldCome,
                            'time' => time(),
                        ];
                        $rico = $RecordTransferAccounts->add_transfer($enterData);
                        if (!$rico) {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '转账失败'];
                        }
                        //添加转出人记录
                        $comeData = [
                            'uid' => $user['uid'],
                            'tid' => $enterId,
                            'type' => $type,
                            'money' => -$money,
                            'transfer' => $recipient['uid'],
                            'user_name' => $recipient['user_name'],
                            'nickname' => $user['user_name'],
                            'remark' => $credit . ':支出之前,该用户' . $credit . '余额为:' . $userCreditOld,
                            'time' => time(),
                        ];
                        $rico = $RecordTransferAccounts->add_transfer($comeData);
                        if ($rico == false) {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '转账失败'];
                        } else {
                            DB::commit();  //提交
                            Log::info('转账人 ' . $user['user_name'] . " " . $user['name'] . ' 转账前: 的 ' . $credit . ' -- ' . $userCreditOld . ' || 转账后:剩余的 ' . $credit . ' -- ' . $expend);
                            Log::info('转账金额:' . $money);
                            Log::info('收账人 ' . $recipient['user_name'] . " " . $recipient['name'] . ' 转账前: 的 ' . $credit . ' -- ' . $userCreditOldCome . ' || 转账后:剩余的 ' . $credit . ' -- ' . $income);
                            return ['code' => 1, 'data' => '交易成功'];
                        }
                    } else {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '转账失败'];
                    }
                } else {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '转账失败'];
                }
                break;
            case 'estimate': //检查转账人是否存在
                $recipient = $MemberModel->find_members(['name' => $data['user']['phone']], ['uid', 'phone', 'user_name']);
                if (empty($recipient) || $recipient['uid'] == $uid) {
                    return ['code' => 0, 'data' => '没有对方数据'];
                } else {
                    $recipient['user_name'] = empty($recipient['user_name']) ? $recipient['phone'] : $recipient['user_name'];
                    return ['code' => 1, 'data' => $recipient];
                }
                break;
            case 'referrer': //注册检查分享人
                $recipient = $MemberModel->find_members(['name' => $data['user']['phone']], ['uid', 'phone', 'user_name', 'by_num']);
                if (empty($recipient)) {
                    return ['code' => 0, 'data' => '没有对方数据'];
                } else {
                    $recipient['user_name'] = empty($recipient['user_name']) ? $recipient['phone'] : $recipient['user_name'];
                    return ['code' => 1, 'data' => $recipient];
                }
                break;
            case 'storesCase':

                $storesLanLng = StoresCenter::where(['number' => $data['stores_number'], 'type' => 1])->value('latitude');
                if ($storesLanLng) {
                    $storesLanLng = explode(',', $storesLanLng);
                    $storesLanLng = $storesLanLng[1] . ',' . $storesLanLng[0];
                    return ['code' => 1, 'data' => $storesLanLng];
                } else {
                    return ['code' => 0, 'data' => '该门店不存在！'];
                }

                break;
        }
    }

    /**
     * 积分兑换
     */
    public function exchange(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        //会员表
        $MemberModel = new Members();
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //转账记录表
        $RecordTransferAccounts = new RecordTransferAccounts();
        $users = $MemberModel->find_members(['uid' => $user->uid], ['uid', 'credit1', 'credit2', 'credit5', 'password_pay', 'salting_pay', 'is_withdraw']);
        if (empty($data['type'])) {
            return ['code' => 0, 'data' => '请选择积分类型'];
        }
        if (empty($data['money'])) {
            return ['code' => 0, 'data' => '请输入转账金额'];
        }

        if (ENCRYPTION($data['password'], $user['salting_pay']) != $user['password_pay']) {
            return ['code' => 0, 'data' => '支付密码错误！'];
        }
        $money = intval($data['money']);
        //参与积分换成积分
        if ($data['type'] == 1) {
            if ($users['credit2'] < $money) {
                return ['code' => 0, 'data' => '金额超出了您承受的范围！'];
            }
            DB::beginTransaction(); //开启事务
            //减
            $comeSub = bcsub($users['credit2'], $money, 2);
            //转出人
            $come = $MemberModel->where(['uid' => $user['uid']])->update(['credit2' => $comeSub]);
            //加
            $enterAdd = bcadd($users['credit1'], $money, 2);
            //进人
            $enter = $MemberModel->where(['uid' => $user['uid']])->update(['credit1' => $enterAdd]);
            if (!$enter || !$come) {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '兑换失败'];
            }
            //查询修改后的用户余额
//            $expend = Members::where('uid', $user['uid'])->value($creditNnem);
//            $income = Members::where('uid', $recipient['uid'])->value($creditNnem);
            $ordersn = ORDER_SN();
            $Transaction0 = [
                'uid' => $user['uid'],
                'ordersn' => $ordersn,
                'money' => -$money,
                'type' => 2, //1 订单 2 转账 3 提现
                'time' => time(),
                'explain' => '参与积分兑换成积分',
                'remark' => '兑换支出之前,该用户' . '参与积分余额为:' . $users['credit2']
            ];
            $Transaction1 = [
                'uid' => $user['uid'],
                'ordersn' => $ordersn,
                'money' => $money,
                'type' => 2, //1 订单 2 转账 3 提现
                'time' => time(),
                'explain' => '积分转入',
                'remark' => '兑换收入之前,该用户' . '积分余额为:' . $users['credit1']
            ];
            $enterId = $RecordTransaction->add_transaction($Transaction0);
            $comeId = $RecordTransaction->add_transaction($Transaction1);
            if ($enterId && $comeId) {
                //添加转进人记录
                $enterData = [
                    'uid' => $user['uid'],
                    'tid' => $comeId,
                    'type' => 3,
                    'money' => $money,
                    'transfer' => $user['uid'],
                    'user_name' => $user['user_name'],
                    'nickname' => $user['nickname'],
                    'remark' => '兑换收入之前,该用户' . '积分余额为:' . $users['credit1'],
                    'time' => time(),
                ];
                $rico = $RecordTransferAccounts->add_transfer($enterData);
                if (!$rico) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '转账失败'];
                }
                //添加转出人记录
                $comeData = [
                    'uid' => $user['uid'],
                    'tid' => $enterId,
                    'type' => 1,
                    'money' => -$money,
                    'transfer' => $user['uid'],
                    'user_name' => $user['user_name'],
                    'nickname' => $user['user_name'],
                    'remark' => '兑换支出之前,该用户' . '余额为:' . $users['credit2'],
                    'time' => time(),
                ];
                $rico = $RecordTransferAccounts->add_transfer($comeData);
                if ($rico == false) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '转账失败'];
                } else {
                    DB::commit();  //提交
//                        Log::info('转账人 ' . $user['user_name'] . " " . $user['name'] . ' 转账前: 的 ' . $credit . ' -- ' . $userCreditOld . ' || 转账后:剩余的 ' . $credit . ' -- ' . $expend);
//                        Log::info('转账金额:' . $money);
//                        Log::info('收账人 ' . $recipient['user_name'] . " " . $recipient['name'] . ' 转账前: 的 ' . $credit . ' -- ' . $userCreditOldCome . ' || 转账后:剩余的 ' . $credit . ' -- ' . $income);
                    return ['code' => 1, 'data' => '交易成功'];
                }
            } else {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '兑换失败'];
            }

        }
        //分享积分换成积分
        if ($data['type'] == 2) {
            if ($users['credit5'] < $money) {
                return ['code' => 0, 'data' => '金额超出了您承受的范围！'];
            }
            DB::beginTransaction(); //开启事务
            //减
            $comeSub = bcsub($users['credit5'], $money, 2);
            //转出人
            $come = $MemberModel->where(['uid' => $user['uid']])->update(['credit5' => $comeSub]);
            //加
            $enterAdd = bcadd($users['credit1'], $money, 2);
            //进人
            $enter = $MemberModel->where(['uid' => $user['uid']])->update(['credit1' => $enterAdd]);
            if (!$enter || !$come) {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '兑换失败'];
            }
            //查询修改后的用户余额
//            $expend = Members::where('uid', $user['uid'])->value($creditNnem);
//            $income = Members::where('uid', $recipient['uid'])->value($creditNnem);
            $ordersn = ORDER_SN();
            $Transaction0 = [
                'uid' => $user['uid'],
                'ordersn' => $ordersn,
                'money' => -$money,
                'type' => 2, //1 订单 2 转账 3 提现
                'time' => time(),
                'explain' => '分享积分兑换成积分',
                'remark' => '兑换支出之前,该用户' . '分享积分余额为:' . $users['credit5']
            ];
            $Transaction1 = [
                'uid' => $user['uid'],
                'ordersn' => $ordersn,
                'money' => $money,
                'type' => 2, //1 订单 2 转账 3 提现
                'time' => time(),
                'explain' => '积分转入',
                'remark' => '兑换收入之前,该用户' . '积分余额为:' . $users['credit1']
            ];
            $enterId = $RecordTransaction->add_transaction($Transaction0);
            $comeId = $RecordTransaction->add_transaction($Transaction1);
            if ($enterId && $comeId) {
                //添加转进人记录
                $enterData = [
                    'uid' => $user['uid'],
                    'tid' => $comeId,
                    'type' => 3,
                    'money' => $money,
                    'transfer' => $user['uid'],
                    'user_name' => $user['user_name'],
                    'nickname' => $user['nickname'],
                    'remark' => '兑换收入之前,该用户' . '积分余额为:' . $users['credit1'],
                    'time' => time(),
                ];
                $rico = $RecordTransferAccounts->add_transfer($enterData);
                if (!$rico) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '兑换失败'];
                }
                //添加转出人记录
                $comeData = [
                    'uid' => $user['uid'],
                    'tid' => $enterId,
                    'type' => 2,
                    'money' => -$money,
                    'transfer' => $user['uid'],
                    'user_name' => $user['user_name'],
                    'nickname' => $user['nickname'],
                    'remark' => '兑换支出之前,该用户' . '分享积分为:' . $users['credit5'],
                    'time' => time(),
                ];
                $rico = $RecordTransferAccounts->add_transfer($comeData);
                if ($rico == false) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '兑换失败'];
                } else {
                    DB::commit();  //提交
//                        Log::info('转账人 ' . $user['user_name'] . " " . $user['name'] . ' 转账前: 的 ' . $credit . ' -- ' . $userCreditOld . ' || 转账后:剩余的 ' . $credit . ' -- ' . $expend);
//                        Log::info('转账金额:' . $money);
//                        Log::info('收账人 ' . $recipient['user_name'] . " " . $recipient['name'] . ' 转账前: 的 ' . $credit . ' -- ' . $userCreditOldCome . ' || 转账后:剩余的 ' . $credit . ' -- ' . $income);
                    return ['code' => 1, 'data' => '交易成功'];
                }
            } else {
                DB::rollback();  //回滚
                return ['code' => 0, 'data' => '兑换失败'];
            }

        }


    }

    /**
     * 提现
     */
    public function withdraw()
    {
        return view('Home.member.withdraw');
    }

    /**
     * 添加银行卡
     */
    public function bank()
    {
        return view('Home.member.bank');
    }

    /**
     * 我的银行卡
     */
    public function banklist()
    {
        return view('Home.member.banklist');
    }

    /**
     * 股东分成
     */
    public function Shareholders()
    {
        return view('Home.shareholder.index');
    }

    /**
     * 添加银行卡
     */
    public function AddBank(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
        $data['bank']['uid'] = $user->uid;
        //银行卡列表
        $BankCard = new BankCard();
        switch ($data['class']) {
            case 'select': //查询
                $rico = $BankCard->get_bank($user->uid);
                $withdraw = RecordWithdraw::where(['uid' => $user->uid])->select('status', 'money', 'remarks', 'withdraw_time')->get()->toArray();
                if ($withdraw) {
                    foreach ($withdraw as $k => $v) {
                        switch ($v['status']) {
                            case -1:
                                $withdraw[$k]['statu'] = "已驳回";
                                break;
                            case 0:
                                $withdraw[$k]['statu'] = "申请中";
                                break;
                            case 1:
                                $withdraw[$k]['statu'] = "已处理";
                                break;
                        }
                        $withdraw[$k]["withdraws_time"] = date('Y-m-d H:i:s', $v["withdraw_time"]);
                    }
                }
                if ($rico) {
                    return ['code' => 1, 'data' => $rico, 'withdraw' => $withdraw];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'add':    //添加 or 修改
                if ($data['bank']['id']) { //修改
                    $rico = $BankCard->where('id', $data['bank']['id'])->update($data['bank']);
                } else {
                    $rico = $BankCard->create($data['bank']);
                }
                if ($rico) {
                    return ['code' => 1, 'data' => '设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'find':   //查询一条数据
                $bank = $BankCard->where('id', $data['id'])->first();
                if ($bank) {
                    return ['code' => 1, 'data' => $bank];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'delete': //删除
                if ($data['id']) {
                    $rico = $BankCard->where('id', $data['id'])->delete();
                    if ($rico) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                } else {
                    return ['code' => 0, 'data' => '数据错误'];
                }
                break;
        }
    }

    public function feeSetting()
    {

        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        if ($Poundage) {
            return ['code' => 1, 'data' => $Poundage];
        } else {
            return ['code' => 0, 'data' => '暂无数据！'];
        }

    }

    /**
     * 提现记录
     */
    public function withdrawPay(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
//        $data['user']['uid'] = $user->uid;
        //会员表
        $UserModel = new Members();
        //银行卡列表
        $BankCard = new BankCard();
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //提现记录表
        $RecordWithdraw = new RecordWithdraw();
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        switch ($data['class']) {
            case 'select': //查询
                $rico = RecordWithdraw::where('uid', $user['uid'])->get()->toArray();
                if ($rico) {
                    return ['code' => 1, 'data' => $rico];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'add':    //添加
                $users = $UserModel->find_members(['uid' => $user->uid], ['uid', 'credit1', 'credit2', 'credit5', 'password_pay', 'salting_pay', 'is_withdraw']);

                if (empty($data['user']['withdrawal_type'])) {
                    return ['code' => 0, 'data' => '提现金额类型不能为空'];
                }
                $money = floatval($data['user']['money']);
                if ($money < 0 || $money % $Poundage->withdrawal_money != 0) {
                    return ['code' => 0, 'data' => '请输入正确的金额！'];
                }
                if ($users['is_withdraw'] != 1) {
                    return ['code' => 0, 'data' => '提现暂未开启！'];
                }

                if (empty($data['user']['beneficiary_name'])) {

                    return ['code' => 0, 'data' => '收款名称不能为空'];
                }
                if (empty($data['user']['collection_number'])) {

                    return ['code' => 0, 'data' => '收款账号不能为空'];
                }
                if (empty($data['user']['account_name'])) {

                    return ['code' => 0, 'data' => '开户名不能为空'];
                }
                if (empty($data['user']['ip'])) {

                    return ['code' => 0, 'data' => '开户行不能为空'];
                }
                if (empty($data['user']['name'])) {
                    return ['code' => 0, 'data' => '验证码不能为空！'];
                }
                $phone = $user['name'];
                $rand = Session::get('register_code' . $phone)['rand'];
                if ($rand != intval($data['user']['name'])) {
                    return ['code' => 0, 'data' => '验证码不正确！'];
                }
                if ($data['user']['withdrawal_type'] == 1) {
                    DB::beginTransaction(); //开启事务
                    if ($users['credit1'] < $money) {
                        return ['code' => 0, 'data' => '电子积分不足！'];
                    }
                    if (ENCRYPTION($data['user']['password'], $users['salting_pay']) != $users['password_pay']) {
                        return ['code' => 0, 'data' => '支付密码错误！'];
                    }

                    //平台手续费
                    $procedure = $money * ($Poundage->poundage * 0.01);
                    $usersData = [
                        'credit1' => $users['credit1'] - $money,
                    ];
                    //时间
                    $actual_money = $money - $procedure;
                    $rico = $UserModel->modification(['uid' => $user->uid], $usersData);
                    if ($rico) {
                        $deposit = [
                            'uid' => $user->uid,
                            'ordersn' => ORDER_SN(),
                            'money' => -$money,
                            'type' => 3, //1 订单 2 转账 3 提现
                            'time' => time(),
                            'explain' => '电子积分提现',
                            'updated_at' => date('Y-m-d H:i:s', time()),
                            'created_at' => date('Y-m-d H:i:s', time()),
                        ];
                        $orderId = $RecordTransaction->add_transaction($deposit);

                        if ($orderId) {
                            $order = [
                                'uid' => $user->uid,
                                'tid' => $orderId,
                                'money' => $money,
                                'beneficiary_name' => $data['user']['beneficiary_name'], //收款名称
                                'account_name' => $data['user']['account_name'], //开户名
                                'collection_number' => intval($data['user']['collection_number']), //收款账号
                                'actual_money' => $actual_money,
                                'procedure' => $procedure,
                                'status' => 0,
                                'ip' => $data['user']['ip'],
                                'withdrawal_type' => 1,//积分提现
                                'withdraw_time' => time(),
                                'updated_at' => date('Y-m-d H:i:s', time()),
                                'created_at' => date('Y-m-d H:i:s', time()),
                            ];
                            $Record = $RecordWithdraw->add_withdraw($order);
                            if ($Record) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => '申请成功！'];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '支付失败！'];
                            }
                        } else {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '支付失败！'];
                        }
                    } else {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '支付失败！'];
                    }
                }
                if ($data['user']['withdrawal_type'] == 2) {
                    DB::beginTransaction(); //开启事务
                    if ($users['credit2'] < $money) {
                        return ['code' => 0, 'data' => '奖励积分不足！'];
                    }
                    if (ENCRYPTION($data['user']['password'], $users['salting_pay']) != $users['password_pay']) {
                        return ['code' => 0, 'data' => '支付密码错误！'];
                    }

                    //平台手续费
                    $procedure = $money * ($Poundage->poundage * 0.01);
                    $usersData = [
                        'credit2' => $users['credit2'] - $money,
                    ];
                    //时间
                    $actual_money = $money - $procedure;
                    $rico = $UserModel->modification(['uid' => $user->uid], $usersData);
                    if ($rico) {
                        $deposit = [
                            'uid' => $user->uid,
                            'ordersn' => ORDER_SN(),
                            'money' => -$money,
                            'type' => 3, //1 订单 2 转账 3 提现
                            'time' => time(),
                            'explain' => '奖励积分提现',
                            'updated_at' => date('Y-m-d H:i:s', time()),
                            'created_at' => date('Y-m-d H:i:s', time()),
                        ];
                        $orderId = $RecordTransaction->add_transaction($deposit);

                        if ($orderId) {
                            $order = [
                                'uid' => $user->uid,
                                'tid' => $orderId,
                                'money' => $money,
                                'beneficiary_name' => $data['user']['beneficiary_name'], //收款名称
                                'account_name' => $data['user']['account_name'], //开户名
                                'collection_number' => intval($data['user']['collection_number']), //收款账号
                                'actual_money' => $actual_money,
                                'procedure' => $procedure,
                                'status' => 0,
                                'ip' => $data['user']['ip'],
                                'withdrawal_type' => 2,//奖励积分
                                'withdraw_time' => time(),
                                'updated_at' => date('Y-m-d H:i:s', time()),
                                'created_at' => date('Y-m-d H:i:s', time()),
                            ];
                            $Record = $RecordWithdraw->add_withdraw($order);
                            if ($Record) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => '申请成功！'];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '支付失败！'];
                            }
                        } else {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '支付失败！'];
                        }
                    } else {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '支付失败！'];
                    }
                }
                break;
            case 'find':   //查询一条数据
                $bank = $BankCard->where('id', $data['id'])->first();
                if ($bank) {
                    return ['code' => 1, 'data' => $bank];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'delete': //删除
                if ($data['id']) {
                    $rico = $BankCard->where('id', $data['id'])->delete();
                    if ($rico) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                } else {
                    return ['code' => 0, 'data' => '数据错误'];
                }
                break;
        }
    }

    /**
     * 我的交易记录页面
     */
    public function myrecord()
    {
        return view('Home.member.myrecord');
    }

    /**
     * 我的交易记录详情
     */
    public function recordDetail(Request $request)
    {
        $id = $request->get('id');
        $data = RecordBonus::where(['tid' => $id])->first();
        return view('Home.member.recordDetail', ['data' => $data]);
    }

    /**
     * 交易记录
     */
    public function record(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
        //会员表
        $UserModel = new Members();
        //银行卡列表
        $BankCard = new BankCard();
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //提现记录表
        $RecordWithdraw = new RecordWithdraw();
        switch ($data['class']) {
            case 'select': //查询
                $rico = $RecordTransaction->from('record_transaction as a')
                    ->where(['a.uid' => $user->uid])
                    ->select('a.*')
                    ->orderBy('id', 'desc')
                    ->paginate(5);
                if ($rico) {
                    $recordNum = $RecordTransaction->where(['uid' => $user['uid'], 'type' => 5])->where('money', '>', 0)->sum('money');

                    return ['code' => 1, 'data' => $rico, 'recordNum' => $recordNum];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'stores_profit': //查询对应门店的返币收益
                //查出该门店对应的门店编号
                $thisStoreNumber = StoresCenter::where(['id' => $data['id']])->value("number");
                $rico = StoresProfitRecord::where(['store_number' => $thisStoreNumber])
                    ->select('currency', 'source_store', 'addtime', 'profit_type', 'consum_type', 'ordersn')
                    ->orderBy('addtime', 'desc')
                    ->paginate(5);

                foreach ($rico as $k => $v) {
                    switch ($v['profit_type']) {
                        case 1:
                            $v['profit_type'] = '终身门店身份收益(2%)';
                            break;
                        case 2:
                            $v['profit_type'] = '消费门店身份收益(3%)';
                            break;
                        default:
                            $v['profit_type'] = '';
                            break;
                    }
                    switch ($v['consum_type']) {
                        case 1:
                            $v['consum_type'] = '老会员绑定门店报单';
                            break;
                        case 2:
                            $v['consum_type'] = '老会员绑定门店复销';
                            break;
                        case 3:
                            $v['consum_type'] = '并未绑定门店';
                            break;
                        default:
                            $v['consum_type'] = '';
                            break;
                    }
                }
                if ($rico) {
                    $recordNum = StoresProfitRecord::where(['store_number' => $thisStoreNumber])->where('currency', '>', 0)->sum('currency');
                    return ['code' => 1, 'data' => $rico, 'recordNum' => $recordNum];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
        }
    }


    /**
     * 我的团队
     */
    public function partners(Request $request)
    {
        $name = $request->get('name');
        $user = session('home_user');
        if (empty($name)) {
            $name = $user->phone;
        }
        $MembersModel = new Members();
        $countMember = $MembersModel->where(['phone' => $name])->count();
        if (empty($countMember)) {
            return redirect()->back()->withErrors('无效号码');
        }
        //查询当前用户
        $memberInfo = $MembersModel->find_members(['phone' => $name], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area'], ['name' => $name]);
        if ($memberInfo['uid'] < $user->uid) {
            return redirect()->back()->withErrors('无效号码');
        }
        if ($memberInfo) {
            $data = $this->subordinate($memberInfo['uid'], $memberInfo['phone']);
        }
        $memberInfo['children'] = $data;
        $memberInfo['name'] = $name;
        //判断格式
        if (!$memberInfo) {
            return ['code' => 0, 'data' => '无效号码'];
        }
        return view('Home.member.partners', ['data' => $memberInfo]);
    }

    //第一层
    public function subordinate($uid = null, $name = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            $data = [
                0 => [
                    'name' => '空点位',
                    'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=A&name=' . $name . '">点击注册<br>A</a>',
                    'className' => 'product-dept',
                ],
                1 => [
                    'name' => '空点位',
                    'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=B&name=' . $name . '">点击注册<br>B</a>',
                    'className' => 'product-dept',
                ],
            ];
        } else {
            $count = count($memberInfo);
            if ($count == 2) {
                foreach ($memberInfo as $k => $v) {
                    $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
                    $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
                    $className = ($v['area'] == 'A') ? 'middle-level' : '';
                    $data[] = [
                        'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                        'className' => $className,
                        'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                        'children' => $this->subordinate2($v['uid'], $v['phone'])
                    ];
                }
            } else {
                foreach ($memberInfo as $k => $v) {
                    $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
                    $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
                    if ($v['area'] == 'A') {
                        $data = [
                            0 => [
                                'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                                'className' => 'middle-level',
                                'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                                'children' => $this->subordinate2($v['uid'], $v['phone'])
                            ],
                            1 => [
                                'name' => '空点位',
                                'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=B&name=' . $name . '">点击注册<br>B</a>',
                                'className' => 'product-dept',
                            ]
                        ];
                    } elseif ($v['area'] == 'B') {
                        $data = [
                            0 => [
                                'name' => '空点位',
                                'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=A&name=' . $name . '">点击注册<br>A</a>',
                                'className' => 'product-dept',
                            ],
                            1 => [
                                'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                                'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                                'children' => $this->subordinate2($v['uid'], $v['phone'])
                            ]
                        ];
                    }
                }
            }
        }
        return json_encode($data);
    }

    //第二层
    public function subordinate2($uid = null, $name = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            $data = [
                0 => [
                    'name' => '空点位',
                    'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=A&name=' . $name . '">点击注册<br>A</a>',
                    'className' => 'product-dept',
                ],
                1 => [
                    'name' => '空点位',
                    'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=B&name=' . $name . '">点击注册<br>B</a>',
                    'className' => 'product-dept',
                ],
            ];
        } else {
            $count = count($memberInfo);
            if ($count == 2) {
                foreach ($memberInfo as $k => $v) {
                    $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
                    $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
                    $className = ($v['area'] == 'A') ? 'middle-level' : '';
                    $data[] = [
                        'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                        'className' => $className,
                        'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                        'children' => $this->subordinate3($v['uid'], $v['phone'])
                    ];
                }
            } else {
                foreach ($memberInfo as $k => $v) {
                    $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
                    $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
                    if ($v['area'] == 'A') {
                        $data = [
                            0 => [
                                'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                                'className' => 'middle-level',
                                'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                                'children' => $this->subordinate3($v['uid'], $v['phone'])
                            ],
                            1 => [
                                'name' => '空点位',
                                'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=B&name=' . $name . '">点击注册<br>B</a>',
                                'className' => 'product-dept',
                            ]
                        ];
                    } elseif ($v['area'] == 'B') {
                        $data = [
                            0 => [
                                'name' => '空点位',
                                'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=A&name=' . $name . '">点击注册<br>A</a>',
                                'className' => 'product-dept',
                            ],
                            1 => [
                                'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                                'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                                'children' => $this->subordinate3($v['uid'], $v['phone'])
                            ]
                        ];
                    }
                }
            }
        }
        return $data;
    }

    //第三层
    public function subordinate3($uid = null, $name = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            $data = [
                0 => [
                    'name' => '空点位',
                    'title' => ' <br><a href="/home/member/register?nodes=' . $uid . '&area=A&name=' . $name . '">点击注册<br>A</a>',
                    'className' => 'product-dept',
                ],
                1 => [
                    'name' => '空点位',
                    'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=B&name=' . $name . '">点击注册<br>B</a>',
                    'className' => 'product-dept',
                ],
            ];
        } else {
            $count = count($memberInfo);
            if ($count == 2) {
                foreach ($memberInfo as $k => $v) {
                    $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
                    $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
                    $className = ($v['area'] == 'A') ? 'middle-level' : '';
                    $data[] = [
                        'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                        'className' => $className,
                        'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                        'children' => []
                    ];
                }
            } else {
                foreach ($memberInfo as $k => $v) {
                    $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
                    $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
                    if ($v['area'] == 'A') {
                        $data = [
                            0 => [
                                'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                                'className' => 'middle-level',
                                'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                                'children' => []
                            ],
                            1 => [
                                'name' => '空点位',
                                'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=B&name=' . $name . '">点击注册<br>B</a>',
                                'className' => 'product-dept',
                            ]
                        ];
                    } elseif ($v['area'] == 'B') {
                        $data = [
                            0 => [
                                'name' => '空点位',
                                'title' => '<br><a href="/home/member/register?nodes=' . $uid . '&area=A&name=' . $name . '">点击注册<br>A</a>',
                                'className' => 'product-dept',
                            ],
                            1 => [
                                'name' => MOBILE_PHONE_HIDDEN($v['phone']),
                                'title' => '<a href="/home/member/partners?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '<br/>' . $registered . '<br/>' . $time . '</a>',
                                'children' => []
                            ]
                        ];
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 会员注册
     */
    public function register(Request $request)
    {
        $data = $request->all();
        $data['nodes'] = empty($data['nodes']) ? '' : $data['nodes'];
        $data['area'] = empty($data['area']) ? '' : $data['area'];
        return view('Home.member.register', $data);
    }

    /**
     * 用户资料
     */
    public function editInfo(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $user = session('home_user');
        //会员表
        $microModel = new MicroMall();
        $micro = $microModel->where('id', 1)->first();
        $PoundageModel = new Poundage();
        $UserModel = new Members();
        switch ($data['class']) {
            case 'find': //查询我的数据
                $user = session('home_user');
                $userData = $UserModel
                    ->where('uid', $user['uid'])
                    ->select('name', 'user_name', 'voucher', 'tiny_level_name', 'platform_profit', 'super_level_name', 'phone', 'uid', 'salting', 'salting_pay', 'super_team_count', 'level_name', 'achievement', 'team_achievement', 'achievement_increment', 'single_achievement', 'level_grade', 'consumption_bonus')
                    ->first();
                $is_partner = SetRebate::where(['name' => $user['name'], 'status' => 1])->count();
                if ($is_partner) {
                    $userData['partner'] = '合伙人';
                }
                $Poundage = $PoundageModel->where('id', 1)->value('subsidy_reward');
                if ($userData['platform_profit'] == 0) {
                    $userData['bonus'] = 0.00;
                } else {
                    $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                    $endToday = mktime(23, 59, 58, date('m'), date('d'), date('Y'));
                    $record = RecordList::where('time', '>=', $beginToday)->where('time', '<=', $endToday)->where('type', '=', 1)->first();
                    if ($record) {
                        $userData['bonus'] = number_format($record['single'] * $userData['voucher'], 2);
                    } else {
                        $userData['bonus'] = 0.00;
                    }

                }

                //计算还有多少未开放分红会员
                if ($userData['platform_profit'] == 0) {
                    $memberCount = $UserModel->where('uid', '<', $user['uid'])->where('platform_profit', 0)->count();
                    $userData['days'] = $memberCount;
                } else {
                    $userData['days'] = '分红中......';
                }
                if ($userData['achievement'] > $micro['tutor']) {
                    $userData['repurchase'] = "svip";
                } else {
                    $userData['repurchase'] = "vip";
                }
                //广告积分预计总收益
                $micro = ShopOrder::where(['uid' => $user['uid'], 'ordertype' => 2])->where('status', '>=', 1)->value('price');
                $userData['expect'] = number_format($micro * 2, 2);
                if ($userData) {
                    return ['code' => 1, 'data' => $userData];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            //修改资料
            case "edit":
                if ($data['UserInfo']) {
                    $user = session('home_user');
//                    if ($user['phone'] != $data['UserInfo']['phone']) {
                    $newData = [
                        'phone' => $data['UserInfo']['phone'],
                        'user_name' => $data['UserInfo']['user_name'],

                    ];
                    $userRow = $UserModel->where('uid', $data['uid'])->update($newData);
                    if ($userRow) {
                        return ['code' => 1, 'data' => '修改成功'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }

                }
                break;
            //修改登陆密码
            case 'loginPass':
                if ($data['UserInfo']) {
                    $pass = ENCRYPTION($data['UserInfo']['password'], $data['UserInfo']['salting']);
                    $passData = $UserModel->where('password', $pass)->first();
                    if (!$passData) {
                        return ['code' => 0, 'data' => '原密码错误'];
                    }
                    $salting = RANDOM();
                    $newData['salting'] = $salting;
                    $newData['password'] = ENCRYPTION($data['UserInfo']['repassword'], $salting);
                    $userRow = $UserModel->where('uid', $passData['uid'])->update(array_only($newData, ['password', 'salting']));
                    if ($userRow) {
                        //Session::put('home_user',null);
                        //return redirect('/home/login/login');
                        return ['code' => 1, 'data' => '修改成功'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }
                }
                break;
            //修改支付密码
            case 'payPass':
                if ($data['UserInfo']) {
                    $pass = ENCRYPTION($data['UserInfo']['password_pay'], $data['UserInfo']['salting_pay']);
                    $passData = $UserModel->where('password_pay', $pass)->first();
                    if (!$passData) {
                        return ['code' => 0, 'data' => '原密码错误'];
                    }
                    $salting = RANDOM();
                    $newData['salting_pay'] = $salting;
                    $newData['password_pay'] = ENCRYPTION($data['UserInfo']['repassword'], $salting);
                    $userRow = $UserModel->where('uid', $passData['uid'])->update(array_only($newData, ['password_pay', 'salting_pay']));
                    if ($userRow) {
                        return ['code' => 1, 'data' => '修改成功'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }
                }
                break;
            //代理申请
            case 'apply':
                if ($data['address']) {
                    $user = session('home_user');
                    //省代理
                    if ($data['address']['type'] == 0) {
                        $province = Apply::where(['province' => $data['address']['province'], 'status' => 1])->first();
                        if ($province) {
                            return ['code' => 0, 'data' => $data['address']['province'] . '已有省代'];
                        }
                    } elseif ($data['address']['type'] == 1) {
                        $city = Apply::where(['city' => $data['address']['city'], 'status' => 1])->first();
                        if ($city) {
                            return ['code' => 0, 'data' => $data['address']['city'] . '已有市代'];
                        }
                    } else {
                        $district = Apply::where(['district' => $data['address']['district'], 'status' => 1])->first();
                        if ($district) {
                            return ['code' => 0, 'data' => $data['address']['district'] . '已有县代'];
                        }
                    }
                    $data['address']['uid'] = $user['uid'];
                    $data['address']['user'] = $user['name'];
                    $data['address']['name'] = $user['user_name'];
                    $data['address']['phone'] = $user['phone'];
                    $data['address']['uid'] = $user['uid'];
                    $userRoic = Apply::create($data['address']);
                    if ($userRoic) {
                        return ['code' => 1, 'data' => '申请成功,等带审核'];
                    } else {
                        return ['code' => 0, 'data' => '申请失败'];
                    }
                }
                break;
            //申请状态
            case 'applylist':
                $user = session('home_user');
                $appleData = Apply::where('user', $user['name'])->get()->toArray();
                if ($appleData) {
                    return ['code' => 1, 'data' => $appleData];
                }
                break;
        }
    }

    //检测会员资料
    public function checkMemberInfo(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        };
        $user = session('home_user');
        //会员表
        $UserModel = new Members();
        $userInfo = $UserModel->where('uid', $user['uid'])->first();
        if (empty($userInfo['phone']) || empty($userInfo['user_name'])) {
            return redirect('/home/member/estate');
        }
    }

    /**
     * 报单商城支付
     */
    public function exMall(Request $request)
    {
        $addressid = $request->get('addressid');
        $OrderId = $request->get('id');

        $latitudes = $request->get('latitudes');

        $storeNumber = $request->get('stores_number');
        $storeNumber = $storeNumber == '' ? '0' : "$storeNumber";
        $nearbyStores = $request->get('nearbyStores');
        $specs = $request->get('specs');

        if (empty($addressid)) {
            return ['code' => 0, 'data' => '请选择收货地址'];
        }
        //会员表
        $UserModel = new Members();
        $RecordTransaction = new RecordTransaction();
        $StoresProfitRecordModel = new StoresProfitRecord();
        $user = session('home_user');
//        $user = $UserModel->where(['uid' => $user->uid])->first();
        $uid = $user->uid;
        //订单表
        $OrderData = ShopOrder::where(['uid' => $uid, 'id' => $OrderId])->first();
        //支付的价格
        $money = $OrderData['price'];
        //公司id
        $company_id = $user['company_id'];
        //当前登录人
        $user = $UserModel->where(['uid' => $uid])->first()->toArray();
        $rico = FIGURE($user['credit1'], $user['credit2'], $user['credit4'], $user['voucher'], $money);
        $status = ShopOrder::where('id', $OrderId)->select('status')->first();
        if (Session::has('orderPay' . $OrderId) || $status->status == 1) {
            return ['code' => 0, 'data' => '支付中,请勿重复提交'];
        }
        //判断金额
        if ($rico['code'] == 1) {
            Session::put('orderPay' . $OrderId, $OrderId);
            Session::save();
            DB::beginTransaction(); //开启事务
            //系统设置
            $PoundageModel = new Poundage();
            $Poundage = $PoundageModel->find_poundage();
            //超级商城设置
            $ExceedShopModel = new ExceedShop();
            $ExceedShop = $ExceedShopModel->get()->toArray();
            //订单表

            $ShopOrderModel = new ShopOrder();
            $addressDataAdd = Address::where(['id' => $addressid])->select('name', 'phone', 'province', 'city', 'district', 'address')->first();
            $ricoOrder = $ShopOrderModel->where(['id' => $OrderId])->update(['status' => 1, 'stores_number' => $storeNumber, 'paytime' => time(), 'addressid' => $addressid, 'receipt_name' => $addressDataAdd['name'], 'receipt_adr' => $addressDataAdd['province'] . $addressDataAdd['city'] . $addressDataAdd['district'] . $addressDataAdd['address'], 'receipt_phone' => $addressDataAdd['phone']]);
            if (empty($ricoOrder)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $OrderId);
                Session::save();
                return ['code' => 0, 'data' => '支付失败'];
            }


            $this->credit2Record($OrderData['ordersn'], $uid);


            //扣除当前登录的金额
            $userData = [  //推荐人奖励添加 DATA
                'credit1' => $user['credit1'] - $rico['data']['credit1'],
                'credit2' => $user['credit2'] - $rico['data']['credit2'],
                'credit4' => $user['credit4'] - $rico['data']['credit4'],
                'voucher' => $user['voucher'] - $rico['data']['voucher'],
                'super_level' => $user['super_level'], //更改等级
                'super_level_name' => $user['super_level_name'], //更改等级名字
            ];

            $userOrder = $UserModel->where(['uid' => $uid])->update($userData);
            if (empty($userOrder)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $OrderId);
                Session::save();
                return ['code' => 0, 'data' => '交易失败'];
            }
            //交易记录表
            $RecordTransaction = new RecordTransaction();
            $recommendData = [
                'uid' => $uid,
                'ordersn' => $OrderData['ordersn'],
                'money' => -$money,
                'type' => 1,
                'time' => time(),
                'explain' => 'vip升级',
                'company_id' => $company_id,
            ];
            $recommendData['remark'] = '电子币：' . -$rico['data']['credit1'] . '，奖励币：' . -$rico['data']['credit2'] . '，积分：' . -$rico['data']['credit4'] . '，代金券：' . -$rico['data']['voucher'];
            $TransactionId = $RecordTransaction->add_transaction($recommendData);
            if (empty($TransactionId)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $OrderId);
                Session::save();
                return ['code' => 0, 'data' => '交易失败'];
            }

            //超级商城奖金计算
            $super = $this->superShop($uid, $user['referrer'], $ExceedShop, $Poundage, $money, $company_id, $OrderData['ordersn'], 1);
            if (!$super) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $OrderId);
                Session::save();
                return ['code' => 0, 'data' => '奖金计算失败'];
            }

            $inventoryIsNull = 0;
            $OrderMallDatass = unserialize($OrderData['mall_data']);
            foreach ($OrderMallDatass as $k => $v) {
                $storeGoodsInventorys = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $user["stores_number"]])->value('inventory');
                if ($storeGoodsInventorys == 0) {
                    //符合条件跳出循环:
                    $inventoryIsNull = 1;
                    break;
                }
            }

            // 有绑定终身门店,只是复销没有提交对应编号
            if ($storeNumber == '0' && $user["stores_number"] != '0' && $inventoryIsNull == 0) {
                $thisStoreExist = StoresCenter::where(['number' => $user["stores_number"], 'type' => 1])->first();
                if ($thisStoreExist) {
                    $firstMemberStoreUid = $thisStoreExist["uid"];
                    //记录订单之前各会员的奖励币余额记录
                    $this->credit2Record($OrderData['ordersn'], $firstMemberStoreUid);
                }

            }


            //判断是否传入门店编号
            if ($storeNumber != '0') {
                //查询该门店是否存在
                $thisStoreExist = StoresCenter::where(['number' => $storeNumber, 'type' => 1])->first();
                if (!$thisStoreExist) {
                    DB::rollback();  //回滚
                    Session::forget('orderPay' . $OrderId);
                    Session::save();
                    return ['code' => 0, 'data' => '该门店编号不存在！'];
                }
                //如果该门店存在:判断当前用户购买的门店是否是其终身绑定的门店
                //查出该用户绑定的终身门店编号
                if ($user["stores_number"] == '0') {
                    //该用户还未绑定终身门店
                    $memberStoreBind = $UserModel->where(['uid' => $uid])->update(['stores_number' => $storeNumber]);
                    if (!$memberStoreBind) {
                        DB::rollback();  //回滚
                        Session::forget('orderPay' . $OrderId);
                        Session::save();
                        return ['code' => 0, 'data' => '绑定终身门店失败！'];
                    }

                    //记录订单之前各会员的奖励币余额记录
                    $this->credit2Record($OrderData['ordersn'], $thisStoreExist["uid"]);
                } else {
                    //计算返币收益提成
                    //查出该用户第一次消费门店的评分
                    $firstStoreCurrency = RETAIN_TWO($money * (2 / 100));
                    $firstStoreNumber = $user["stores_number"];
                    //现在消费门店该返币额为：
                    $thisStoreCurrency = RETAIN_TWO($money * ($thisStoreExist["score"] / 100));
                    //查出当前消费者绑定的终身门店下的对应的uid
                    $thisUidBindStoreMember = StoresCenter::where(['number' => $user["stores_number"], 'type' => 1])->value("uid");
                    if ($thisUidBindStoreMember) {
                        $credit2Data = [
                            0 => [
                                'number' => $storeNumber,
                                'credit2' => $thisStoreCurrency,
                                'uid' => $thisStoreExist["uid"]
                            ],
                            1 => [
                                'number' => $firstStoreNumber,
                                'credit2' => $firstStoreCurrency,
                                'uid' => $thisUidBindStoreMember
                            ]
                        ];
                    } else {
                        $credit2Data = [
                            0 => [
                                'number' => $storeNumber,
                                'credit2' => $thisStoreCurrency,
                                'uid' => $thisStoreExist["uid"]
                            ]
                        ];
                    }
                    foreach ($credit2Data as $k => $v) {
                        //记录订单之前各会员的奖励币余额记录
                        $this->credit2Record($OrderData['ordersn'], $v["uid"]);
                    }
                }


                //减少用户消费门店的对应商品的库存
                $OrderMallData = unserialize($OrderData['mall_data']);
                foreach ($OrderMallData as $k => $v) {
                    if ($v['num'] != '0') {
                        $storeGoodsNumber = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])
                            ->select('goodsname', 'inventory', 'specs_txt')
                            ->first();

                        if ($specs != "") {
                            $specsDataArr = [];
                            $specsDataStr = '';
                            $specsDataArr1 = [];
                            $specs_txt1 = explode("|", $storeGoodsNumber["specs_txt"]);
                            for ($i = 0; $i < count($specs_txt1); $i++) {
                                $specs_txt2 = explode("--", $specs_txt1[$i]);
                                $specsDataArr[$i] = ['specsStr' => $specs_txt2[0], 'specsNum' => $specs_txt2[1]];
                            }
                            $specsCopy = '[' . $specs . ']';


                            foreach ($specsDataArr as $keys => $values) {

                                if ($specsCopy == $values['specsStr']) {
                                    if (intval($values["specsNum"]) <= 0 || intval($values["specsNum"]) < $v['num']) {
                                        DB::rollback();  //回滚
                                        Session::forget('orderPay' . $OrderId);
                                        Session::save();
                                        return ['code' => 0, 'data' => '该门店商品:' . $storeGoodsNumber["goodsname"] . '规格' . $specsCopy . '库存不足,换成其他规格试试吧!'];
                                        exit;
                                    }
                                    $values["specsNum"] = $values["specsNum"] - $v['num'];
                                }
                                $specsDataArr1[$keys] = implode("--", $values);
                            }
                            $specsDataStr = implode("|", $specsDataArr1);
                            $specsDataDel = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->update(['specs_txt' => $specsDataStr]);
                            if (!$specsDataDel) {
                                DB::rollback();  //回滚
                                Session::forget('orderPay' . $OrderId);
                                Session::save();
                                return ['code' => 0, 'data' => '商品规格详细数据更新失败!'];
                                exit;
                            }
                        }

                        if ($storeGoodsNumber["inventory"] <= 0 || $storeGoodsNumber["inventory"] < $v['num']) {
                            DB::rollback();  //回滚
                            Session::forget('orderPay' . $OrderId);
                            Session::save();
                            return ['code' => 0, 'data' => '该门店商品:' . $storeGoodsNumber["goodsname"] . '库存不足,请提醒商家加货!'];
                            exit;
                        }
                        //减少该门店对应商品的现库存量
                        $StoreInventoryDel = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->decrement('inventory', $v['num']);
                        //增加该门店对应商品的已出售量
                        $StoreSoldAdd = StoresCenterGoods::where(['gid' => $v['goods_id'], 'stores_sn' => $storeNumber])->increment('sold', $v['num']);
                        if (!$StoreInventoryDel || !$StoreSoldAdd) {
                            DB::rollback();  //回滚
                            Session::forget('orderPay' . $OrderId);
                            Session::save();
                            return ['code' => 0, 'data' => '门店商品库存变更失败！'];
                            exit;
                        }
                    }

                }
            }


            DB::commit();  //提交
            Session::forget('orderPay' . $OrderId);
            Session::save();
            $users = Members::where('uid', $user['uid'])->first();
            Session::put('home_user', $users);
            return ['code' => 1, 'data' => '支付成功'];
        } else {
            return ['code' => 0, 'data' => $rico['data']];
        }
    }

    /**
     * 报单价格计算
     * @param Request $request
     * @return array
     */
    public function math_Register(Request $request)
    {
        $data = $request->all();
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->first();
        $user = session('home_user');
        $uid = $user->uid;
        $userData = Members::where('uid', $uid)->first();
        if ($data['level'] == 2) {
            $rico = FIGURE($userData['credit1'], $userData['credit2'], $data['money']);
            if ($rico['code'] == 1) {
                $rico['data']['credit4'] = 0;
            }
        } else {
            if ($data['again'] == 'true') {
                $rico = FIGURE_READ($userData['credit1'], $userData['credit2'], $userData['credit4'], $Poundage['deduction'], $data['money']);
            } else {
                $rico = FIGURE($userData['credit1'], $userData['credit2'], $data['money']);
            }
        }
        return $rico;
    }

    /**
     * 阅读奖励
     * @param $uid
     * @param $point
     * @param $bookId
     * @param $type
     * @param $explain
     * @param $ordersn
     * @return void
     */
    public function addReadRecord($uid, $point, $bookId, $type, $explain, $ordersn)
    {
        $ordersn = empty($ordersn) ? ORDER_SN() : $ordersn;
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => $point,
            'type' => $type,
            'time' => time(),
            'explain' => $explain,
            'company_id' => $bookId,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $point,
            'remark' => '阅读积分 ：' . $point,
            'time' => time(),
            'type' => 1,
            'company_id' => $bookId,
        ];
        $RecordBonus->add_bonus($bonusData);
    }

    /**
     * 添加交易记录
     * @param null $uid 会员id
     * @param null $money 交易总金额
     * @param null $type 交易类型 1 订单 2 转账 3 提现  4充值 5 奖励制度
     * @param string $explain 交易名称
     * @param array $manageMoney 奖励金额 复投金额 平台费金额
     * @param null $company_id 公司id
     */
    public function addOrder($uid = null, $money = null, $type = null, $explain = '', $manageMoney = array(), $company_id = null, $ordersn = '')
    {
        $ordersn = empty($ordersn) ? ORDER_SN() : $ordersn;
        //交易记录表
        $order_uid = ShopOrder::where('ordersn', $ordersn)->value('uid');
        $userName = Members::where('uid', $order_uid)->value('user_name');
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => $money,
            'type' => $type,
            'time' => time(),
            'explain' => $explain,
            'company_id' => $company_id,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $money,
            'remark' => $explain . '：' . $manageMoney['money'] . '，复销币：' . $manageMoney['redelivery'] . '，平台费：' . $manageMoney['platform_fee'],
//            'remark' => $explain . '：' . $money. '，参与积分来源：用户' . $userName . '参与抢购' . ')',
            'time' => time(),
            'type' => 1,
            'company_id' => $company_id,
        ];
        if (empty($manageMoney)) {
            $bonusData['remark'] = '';
        }
        $RecordBonus->add_bonus($bonusData);
    }

    /**
     * 记录订单之前各会员的奖励币余额记录
     * @param int $uid 用户ID
     * @param string $ordersn 统一订单
     * @return array
     */
    public function credit2Record($ordersn, $uid)
    {
        $ShopOrder = new ShopOrder();
        $UserModel = new Members();
        $orderMemberCredit2Datas = [];
        $orderMemberCredit2Uid = [];
        $orderMemberCredit2Uids = [];
        $memberLastCredit2Data = $ShopOrder->where(['ordersn' => $ordersn])->value('last_credit2s');
        if ($memberLastCredit2Data != "") {
            $memberLastCredit2Data = unserialize($memberLastCredit2Data);
        } else {
            $memberLastCredit2Data = [];
        }
        $memberLastCredit2 = [];
        $memberLastData = $UserModel->where(['uid' => $uid])->select('uid', 'name', 'user_name', 'credit1', 'credit2', 'credit5', 'voucher')->first();
        $memberLastCredit2['uid'] = $memberLastData['uid'];
        $memberLastCredit2['name'] = $memberLastData['name'];
        $memberLastCredit2['user_name'] = $memberLastData['user_name'];
        $memberLastCredit2['credit1'] = $memberLastData['credit1'];
        $memberLastCredit2['credit2'] = $memberLastData['credit2'];
        $memberLastCredit2['credit5'] = $memberLastData['credit5'];
//        $memberLastCredit2['voucher'] = $memberLastData['voucher'];
        if ($memberLastCredit2Data) {
            foreach ($memberLastCredit2Data as $key => $value) {
                array_push($orderMemberCredit2Uid, $value['uid']);
            }
            if (!in_array($uid, $orderMemberCredit2Uid)) {
                array_push($memberLastCredit2Data, $memberLastCredit2);
            }
            $Credit2SaveData = serialize($memberLastCredit2Data);
        } else {
            if (count($orderMemberCredit2Datas) > 0) {
                foreach ($orderMemberCredit2Datas as $key => $value) {
                    array_push($orderMemberCredit2Uids, $value['uid']);
                }
                if (!in_array($uid, $orderMemberCredit2Uids)) {
                    array_push($orderMemberCredit2Datas, $memberLastCredit2);
                }
            } else {
                array_push($orderMemberCredit2Datas, $memberLastCredit2);
            }
            $Credit2SaveData = serialize($orderMemberCredit2Datas);
        }
        $ShopOrder->where(['ordersn' => $ordersn])->update(['last_credit2s' => $Credit2SaveData]);
    }


    /**
     * 区域代理分红
     * @param int $money 支付金额
     * @param int $company_id 分公司id
     * @param array $Poundage 系统设置
     * @param null $province 省
     * @param null $city 市
     * @param null $area 区
     * @param string $ordersn 统一订单
     * @return array
     */
    public function agency($money = 0, $company_id = 0, $Poundage = array(), $province = null, $city = null, $area = null, $ordersn = '')
    {
        if ($money < 0 || empty($money)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //会员表
        $UserModel = new Members();
        //查询代理区域
        $userApply = new Apply();
        //查询订单类型
        $orderType = ShopOrder::where('ordersn', $ordersn)->value('ordertype');

        //查询该区域市代理
        $userCity = $userApply->where(['type' => 1, 'city' => $city, 'status' => 1])->get()->toArray();
        $agencyCity = 0;//市代理uid
        if (!empty($userCity)) {
            foreach ($userCity as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($area, $district)) {
                        $agencyCity = $v['uid'];
                    }
                }
            }
            if ($agencyCity != 0) {
                $member = $UserModel->find_members(['uid' => $agencyCity], ['uid', 'credit1', 'credit2', 'credit5', 'type']);
                //计算金额
                $cityMoney = RETAIN_TWO($money * ($Poundage['city'] * 0.01));
                //扣除平台费和复投币
                $recommendMoney = CALCULATE($Poundage, $cityMoney, $orderType);
                if ($member && $member['type'] == 1) {
                    $member['credit2'] += $recommendMoney['money'];
                    $member['credit5'] += $recommendMoney['redelivery'];

                    //记录订单之前各会员的奖励币余额记录
                    $this->credit2Record($ordersn, $member['uid']);
                    //更新会员数据
                    $userAttributes = $UserModel->where(['uid' => $member['uid']])->update($member['attributes']);
                    if ($userAttributes) {
                        //添加记录
                        $this->addOrder($member['uid'], $cityMoney, 5, '市代理分润', $recommendMoney, $company_id, $ordersn);
                    }
                }
            }
        }
        //查询区县代理
        $userDistrict = $userApply->where(['type' => 2, 'city' => $city, 'district' => json_encode($area), 'status' => 1])->first();
        if (!empty($userDistrict)) {
            $member = $UserModel->find_members(['uid' => $userDistrict['uid']], ['uid', 'credit1', 'credit2', 'credit5', 'type']);
            //计算金额
            $areaMoney = RETAIN_TWO($money * ($Poundage['area'] * 0.01));
            //扣除平台费和复投币
            $recommendMoney = CALCULATE($Poundage, $areaMoney, $orderType);
            if ($member && $member['type'] == 1) {
                $member['credit2'] += $recommendMoney['money'];
                $member['credit5'] += $recommendMoney['redelivery'];
                //记录订单之前各会员的奖励币余额记录
                $this->credit2Record($ordersn, $member['uid']);
                //更新会员数据
                $userAttributes = $UserModel->where(['uid' => $member['uid']])->update($member['attributes']);
                if ($userAttributes) {
                    //添加记录
                    $this->addOrder($member['uid'], $areaMoney, 5, '区/县代理分润', $recommendMoney, $company_id, $ordersn);
                }
            }
        }
    }

    /**
     * 股东分红
     * @param int $money 支付金额
     * @param int $company_id 分公司id
     * @param array $Poundage 系统设置
     * @param string $ordersn 统一订单
     * @return array
     */
    public function Shareholder($money = 0, $company_id = 0, $Poundage = array(), $ordersn = '')
    {
        if ($money < 0 || empty($money)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //计算金额
        $recommend = RETAIN_TWO($money * ($Poundage['equity'] * 0.01));
        //会员表
        $UserModel = new Members();
        //查询股东
        $countMember = $UserModel->count_member(['shareholder' => 1]);
        if ($countMember) {
            $member = $UserModel->where(['shareholder' => 1])->get()->toArray();
            $money = RETAIN_TWO($recommend / count($member));
            foreach ($member as $k => $v) {
                //扣除平台费和复投币
                $recommendMoney = CALCULATE($Poundage, $money, 1);
                $v['credit2'] += $recommendMoney['money'];
                $v['credit3'] += $recommendMoney['redelivery'];
                //添加记录
                $this->addOrder($v['uid'], $money, 5, '股东分红', $recommendMoney, $company_id, $ordersn);
                //更新会员数据
                $UserModel->where(['uid' => $v['uid']])->update($v);
            }
        }
    }

    /**
     * @param int $money
     * @param int $company_id
     * @param array $Poundage
     * @param string $ordersn
     * @return array
     * DT内衣股东提成
     */

    public function DT_Shareholder($money = 0, $company_id = 0, $Poundage = array(), $ordersn = '')
    {
        if ($money < 0 || empty($money)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //计算金额
        $recommend = RETAIN_TWO($money * ($Poundage['equity'] * 0.01));
        //会员表
        $UserModel = new Members();
        //查询股东
        $countMember = $UserModel->count_member(['DT_shareholder' => 1]);
        if ($countMember) {
            $member = $UserModel->where(['DT_shareholder' => 1])->get()->toArray();
            $money = RETAIN_TWO($recommend / count($member));
            foreach ($member as $k => $v) {
                //扣除平台费和复投币
                $recommendMoney = CALCULATE($Poundage, $money, 1);
                $v['credit2'] += $recommendMoney['money'];
                $v['credit3'] += $recommendMoney['redelivery'];
                //添加记录
                $this->addOrder($v['uid'], $money, 5, 'DT内衣股东分红', $recommendMoney, $company_id, $ordersn);
                //更新会员数据
                $UserModel->where(['uid' => $v['uid']])->update($v);
            }
        }
    }

    /**
     * 股东分红所有数据列表
     */
    public function ShareholderList()
    {
        return view('Home.shareholder.shareholder_list');
    }

    /**
     * 股东分红单条记录页面
     */
    public function ShareholderDetail()
    {
        return view('Home.shareholder.shareholder_detail');
    }

    /**
     * @param Request $request
     * @return array
     * 获取股东分红数据
     */

    public function getShareholder(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        switch ($data['class']) {
            case 'bonusTotal'://股东总提成
                $arr = array();
                $PoundageModer = new  Poundage();
                $Poundage = $PoundageModer->first();
                if ($user['DT_shareholder'] == 1) {
                    //DT股东总分红
                    $DTRecord = RecordTransaction::where(['uid' => $user->uid, 'type' => 5, 'explain' => 'DT内衣股东分红'])->get()->toArray();
                    $DTtotal = 0;
                    foreach ($DTRecord as $key => $value) {
                        $price = CALCULATE($Poundage, $value['money'], 1);
                        $DTRecord[$key]['money'] = $price['money'];
                    }
                    foreach ($DTRecord as $v) {
                        $DT['money'] = (string)($DTtotal += $v['money']);
                    }
                    if ($DTtotal == 0) {
                        $DT['money'] = $DTtotal = '0.00';
                    }
                    $DT['name'] = 'DT股东总业绩';
                    $DT['type'] = 'DT_shareholder';
                    array_push($arr, $DT);
                }
                if ($user['shareholder'] == 1) {
                    //宝励股东总分红
                    $BLRecord = RecordTransaction::where(['uid' => $user->uid, 'type' => 5, 'explain' => '股东分红'])->get()->toArray();
                    $BLtotal = 0;
                    foreach ($BLRecord as $key => $value) {
                        $price = CALCULATE($Poundage, $value['money'], 1);
                        $BLRecord[$key]['money'] = $price['money'];
                    }
                    foreach ($BLRecord as $v) {
                        $BL['money'] = (string)($BLtotal += $v['money']);
                    }
                    if ($BLtotal == 0) {
                        $BL['money'] = $BLtotal = '0.00';
                    }
                    $BL['name'] = '宝励股东总业绩';
                    $BL['type'] = 'shareholder';
                    array_push($arr, $BL);
                }
                return ['code' => 1, 'data' => $arr];
                break;
            case 'select'://所有提成数据
                switch ($data['type']) {
                    case 'DT_shareholder':
                        $Record = RecordTransaction::where(['uid' => $user->uid, 'type' => 5, 'explain' => 'DT内衣股东分红'])->orderBy('time', 'desc')->get()->toArray();
                        if ($Record) {
                            return ['code' => 1, 'data' => $Record];
                        } else {
                            return ['code' => 0, 'data' => ''];
                        }
                        break;
                    case 'shareholder':
                        $Record = RecordTransaction::where(['uid' => $user->uid, 'type' => 5, 'explain' => '股东分红'])->orderBy('time', 'desc')->get()->toArray();
                        if ($Record) {
                            return ['code' => 1, 'data' => $Record];
                        } else {
                            return ['code' => 0, 'data' => ''];
                        }
                        break;
                }
                break;
            case 'detail'://单条数据详情
                $detail = RecordTransaction::join('record_bonus', 'record_bonus.tid', '=', 'record_transaction.id')
                    ->select(
                        'record_bonus.remark',
                        'record_transaction.ordersn',
                        'record_transaction.money',
                        'record_transaction.type',
                        'record_transaction.explain',
                        'record_transaction.created_at'
                    )
                    ->where('record_transaction.id', $data['id'])
                    ->first();
                if ($detail) {
                    return ['code' => 1, 'data' => $detail];
                } else {
                    return ['code' => 0, 'data' => '参数错误'];
                }
                break;
        }
    }

    /*
* 获取区域代理分润数据
*/
    public function getAgentBonus(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        switch ($data['class']) {
            case 'select'://股东总提成
                $PoundageModer = new  Poundage();
                $Poundage = $PoundageModer->first();
                $bonusRecord = RecordTransaction::where(['uid' => $user->uid, 'type' => 5])
                    ->where('explain', 'like', '%' . '代理分润')
                    ->orderBy('time', 'desc')
                    ->get()->toArray();
                $total = 0;
                $money = array();
                foreach ($bonusRecord as $key => $value) {
                    $price = CALCULATE($Poundage, $value['money'], 1);
                    $money[$key] = $price['money'];
                }
                foreach ($money as $v) {
                    $total += $v;
                }
                if ($total == 0) {
                    $total = '0.00';
                }
                if ($bonusRecord) {
                    return ['code' => 1, 'data' => $bonusRecord, 'total' => (string)$total];
                } else {
                    return ['code' => 1, 'data' => '', 'total' => (string)$total];
                }
                break;
            case 'detail'://单条数据详情
                $detail = RecordTransaction::join('record_bonus', 'record_bonus.tid', '=', 'record_transaction.id')
                    ->select(
                        'record_bonus.remark',
                        'record_transaction.ordersn',
                        'record_transaction.money',
                        'record_transaction.type',
                        'record_transaction.explain',
                        'record_transaction.created_at'
                    )
                    ->where('record_transaction.id', $data['id'])
                    ->first();
                if ($detail) {
                    return ['code' => 1, 'data' => $detail];
                } else {
                    return ['code' => 0, 'data' => '参数错误'];
                }
                break;
        }

    }

    /*
     * 区域代理分红页面
     */
    public function agentBonus()
    {
        return view('Home.regionalagency.index');
    }

    /*
     * 区域代理分红详情页面
     */
    public function bonusDetail()
    {
        return view('Home.regionalagency.regionalagency_list');
    }


    /**
     * 特价商城支付页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function specialShop()
    {
        return view('Home.micro.specialShop');
    }

    /**
     * 特价商城支付
     * @param Request $request
     * @return array
     */
    public function excellentSpecial(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        if (!$data['addressid']) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //会员表
        $UserModel = new Members();
        $user = session('home_user');
        //支付密码
        if (ENCRYPTION($data['zfpassword'], $user['salting_pay']) != $user['password_pay']) {
            return ['code' => 0, 'data' => '支付密码错误！'];
        }
        $uid = $user->uid;
        $referrer = $user->referrer;
        $share = $referrer;//分享人ID
        $puid = $uid;
        $user = $UserModel->where(['uid' => $user->uid])->first();
        $company_id = $user['company_id'];
        //订单id
        $id = $data['id'];
        //订单详情
        $orderComment = ShopOrderComment::where(['orderid' => $id, 'uid' => $uid])->get()->toArray();
        $cost_price = 0;
        $countPoints = 0;
        $pk_integral = 0;
        $is_explosive = 0;
        foreach ($orderComment as $k => $v) {
            $pk_integral = ShopGoods::where('id', $v['goodsid'])->value('pk_integral');
            $is_explosive = ShopGoods::where('id', $v['goodsid'])->value('is_explosive');


        }
        //订单表
        $ShopOrder = new ShopOrder();
        $order = $ShopOrder->where(['id' => $id, 'uid' => $uid])->first();
        if (empty($order)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //订单金额
        $actual_money = $order['price'];
        //只能使用的积分支付
        $freight = $actual_money;
//        $voucher = RETAIN_TWO($actual_money/1000);
        //判断用户是否使用阅读积分
        $rico = FIGURE($user['credit1'], $user['credit2'], $freight);
        $status = ShopOrder::where('id', $id)->select('status')->first();
        if (Session::has('orderPay' . $id) || $status->status == 1) {
            return ['code' => 0, 'data' => '支付中,请勿重复提交'];
        }
        if ($rico['code'] == 1) {
            //系统设置
            $SetPoundage = new Poundage();
            $Poundage = $SetPoundage->where(['id' => 1])->first()->toArray();
            //微商城设置
            $microMall = new MicroMall();
            $micro = $microMall->get()->toArray();
            //第一次请求  带上订单号存Sessoin
            Session::put('orderPay' . $id, $id);
            Session::save();
            DB::beginTransaction();
            $userData = [
                'credit1' => $user['credit1'] - $rico['data']['credit1'],
                'credit2' => $user['credit2'] - $rico['data']['credit2'],
                'achievement' => $user['achievement'] + $freight,
            ];
            $this->credit2Record($order['ordersn'], $uid);
            $userOrder = $UserModel->where(['uid' => $uid])->update($userData);
            if (empty($userOrder)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $id);
                Session::save();
                return ['code' => 0, 'data' => '参数错误'];
            }

            //交易记录表
            $RecordTransaction = new RecordTransaction();
            $recommendData = [
                'uid' => $uid,
                'ordersn' => $order['ordersn'],//关联order表订单编号
                'money' => -$freight,
                'type' => 1,
                'time' => time(),
                'explain' => '优选商城',
                'company_id' => $company_id,
                'remark' => '购物积分：' . -$rico['data']['credit1'] . '，奖金积分：' . -$rico['data']['credit2'],
            ];

            $TransactionId = $RecordTransaction->add_transaction($recommendData);
            if (empty($TransactionId)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $id);
                Session::save();
                return ['code' => 0, 'data' => '参数错误'];
            }
            //实际支付金额
            $money = $rico['data']['credit1'] + $rico['data']['credit2'];
            $addressDataAdd = Address::where(['id' => $data['addressid']])->select('name', 'phone', 'province', 'city', 'district', 'address')->first();
            $saveOrder = $ShopOrder->where(['id' => $id])->update([
                'status' => 1,
                'paytime' => time(),
                'freight' => '包邮',
                'addressid' => $data['addressid'],
                'reward_money' => $money,
                'receipt_name' => $addressDataAdd['name'],
                'receipt_adr' => $addressDataAdd['province'] . $addressDataAdd['city'] . $addressDataAdd['district'] . $addressDataAdd['address'], 'receipt_phone' => $addressDataAdd['phone']]);
            if (empty($saveOrder)) {
                DB::rollback();  //回滚
                Session::forget('orderPay' . $id);
                Session::save();
                return ['code' => 0, 'data' => '参数错误'];
            }
//            //个人消费元宝积分明细
//            if ($is_explosive > 0) {
//                $credit4 = $UserModel->where(['uid' => $uid])->increment('credit4', $is_explosive);
//                if ($credit4) {
//                    $RecordTransaction = new RecordTransaction();
//                    $recommendData = [
//                        'uid' => $uid,
//                        'ordersn' => $order['ordersn'],
//                        'money' => $is_explosive,
//                        'type' => 4,
//                        'time' => time(),
//                        'explain' => '个人消费元宝积分',
//                        'remark' => '个人消费元宝积分：' . $is_explosive,
//                    ];
//                    $TransactionId = $RecordTransaction->add_transaction($recommendData);
//                    if (empty($TransactionId)) {
//                        DB::rollback();  //回滚
//                        return ['code' => 0, 'data' => '交易失败'];
//                    }
//                }
//
//            }
//            //直推奖金计算
//            if ($pk_integral > 0) {
//                $res = $this->bonusSpecial($uid, $user['referrer'], $micro, $Poundage, $actual_money, $company_id, 0, $order['ordersn'], $pk_integral);
//                if (empty($res)) {
//                    DB::rollback();  //回滚
//                    return ['code' => 0, 'data' => '交易失败'];
//                }
//            }
            DB::commit();  //提交
            Session::forget('orderPay' . $id);
            Session::save();
            return ['code' => 1, 'data' => '支付成功'];
        } else {
            return ['code' => 0, 'data' => '余额不足'];
        }
    }

    /**
     * 特价商城奖金计算
     */
    public function bonusSpecial($uid = null, $referrer = null, $micro = array(), $Poundage = array(), $actual_money = null, $company_id = 0, $upgrade = '', $ordersn = '', $money)
    {

        //会员表
        $puid = $uid;
        $user = session('home_user');
        $share = $referrer;//分享人ID
        $referrer = $referrer; //分享人
        $UserModel = new Members();
        $till = 0;
        $money1 = $money;
        $actual_money = $actual_money;
        $money2 = $money;
        $number1 = 1;
        $number2 = 1;//超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->get()->toArray();
        //加权业绩设置
        $bonusModel = new SetBonus();
        $setBonus = $bonusModel->get()->toArray();
        //特价专区设置
        $directModel = new DirectWeighting();
//        $direct = $directModel->get()->toArray();
        $order = ShopOrder::where('ordersn', $ordersn)->first();
        $address = Address::where('id', $order['addressid'])->first();
        $userApply = new Apply();
        //查询市代理
        $cityData = $userApply->where(['type' => 1, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyCity = 0;//市代理uid
        if (!empty($cityData)) {
            foreach ($cityData as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyCity = $v['uid'];
                    }
                }
            }
        }
        $city = $address['city'] . $address['district'];
        $this->bonusAgency($agencyCity, $money, $Poundage, $order['ordersn'], $city);
        return true;
    }


    /**
     * 微商城地址选择页面
     */
    public function choiceAddress()
    {
        return view('Home.member.addressCheckList');
    }

    public function bonusAchievement($uid = null, $referrer = null, $Poundage = array(), $money = null, $company_id = 0, $upgrade = '', $ordersn = '', $type = 0)
    {
        //会员表
        $puid = $uid;
        $user = session('home_user');
        $share = $referrer;//分享人ID
        //业绩设置
        $QualityModel = new SetQuality();
        $Quality = $QualityModel->get()->toArray();
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->get()->toArray();
        $referrer = $referrer; //分享人
        $UserModel = new Members();
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $money6 = $money;
        $money7 = $money;
        $money8 = $money;
        $money9 = $money;
        $number3 = 1;
        $number4 = 1;
        $number5 = 1;
        $number6 = 1;
        $number7 = 1;
        $number8 = 1;
        $number9 = 1;
        $userInfor = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')
            ->select(
                'uid', 'referrer', 'level', 'level_name', 'level_grade',
                'credit1', 'credit2', 'credit5', 'type', 'super_recommend',
                'super_team_count', 'super_small_team_count', 'super_level',
                'super_level_name', 'achievement', 'team_member_count'
            )
            ->get()
            ->toArray();
        foreach ($userInfor as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {
//                  //寻找上级id 微客
                    $referrer = $v['referrer'];
//                    //会员等级升级
//                    if ($type == 0) {
//                        $arrays[$v['uid']] = $v['referrer'];
//                        $v = $this->UpGrade($v, $puid, $ExceedShop,$Quality, $arrays, $share, $money ,2);
//                    }
                    //V1 一阶段奖励
                    if (($v['level'] == 1 && $v['level_grade'] >= 1) || $v['level'] > 1) {
                        $set = SetQuality::where(['level' => 1, 'level_stage' => 1])->first();
                        if ($number3 == 1) {
                            $money3 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                            $recommendMoney = CALCULATE($Poundage, $money3, 1);
                            $number3++;
                            //添加记录
                            if ($v['type'] == 1) {
                                $v['credit2'] += $recommendMoney['money'];
                                $v['credit5'] += $recommendMoney['redelivery'];
                                $this->bonusCredit2($v['uid'], $ordersn);
                                $this->addOrder($v['uid'], $money3, 5, 'V1业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                            }
                        }
                    }
                    //V1 二阶段奖励
                    if ($v['level'] == 1 && $v['level_grade'] >= 2 || $v['level'] > 1) {
                        $set = SetQuality::where(['level' => 1, 'level_stage' => 2])->first();
                        if ($number4 == 1) {
                            $money4 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                            $recommendMoney = CALCULATE($Poundage, $money4, 1);
                            $number4++;
                            //添加记录
                            if ($v['type'] == 1) {
                                $v['credit2'] += $recommendMoney['money'];
                                $v['credit5'] += $recommendMoney['redelivery'];
                                $this->bonusCredit2($v['uid'], $ordersn);
                                $this->addOrder($v['uid'], $money4, 5, 'V1业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                            }
                        }
                    }
                    //V1 三阶段奖励
                    if ($v['level'] == 1 && $v['level_grade'] >= 3 || $v['level'] > 1) {
                        $set = SetQuality::where(['level' => 1, 'level_stage' => 3])->first();
                        if ($number5 == 1) {
                            $money5 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                            $recommendMoney = CALCULATE($Poundage, $money5, 1);
                            $number5++;
                            //添加记录
                            if ($v['type'] == 1) {
                                $v['credit2'] += $recommendMoney['money'];
                                $v['credit5'] += $recommendMoney['redelivery'];
                                $this->bonusCredit2($v['uid'], $ordersn);
                                $this->addOrder($v['uid'], $money5, 5, 'V1业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                            }
                        }
                    }
                    //V2 一阶段奖励
                    if ($v['level'] == 2 && $v['level_grade'] >= 1 || $v['level'] > 2) {
                        $set = SetQuality::where(['level' => 2, 'level_stage' => 1])->first();
                        if ($number6 <= 2) {
                            if ($number6 == 1) {
                                $money6 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                $number6++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money6, 5, 'V2业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money6 = RETAIN_TWO($money6 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                $number6++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money6, 5, 'V2业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                    //V2 二阶段奖励
                    if ($v['level'] == 2 && $v['level_grade'] >= 2 || $v['level'] > 2) {
                        $set = SetQuality::where(['level' => 2, 'level_stage' => 2])->first();
                        if ($number7 <= 2) {
                            if ($number7 == 1) {
                                $money7 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                $number7++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money7, 5, 'V2业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money7 = RETAIN_TWO($money7 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                $number7++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money7, 5, 'V2业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                    //V2 三阶段奖励
                    if ($v['level'] == 2 && $v['level_grade'] >= 3 || $v['level'] > 2) {
                        $set = SetQuality::where(['level' => 2, 'level_stage' => 3])->first();
                        if ($number8 <= 2) {
                            if ($number8 == 1) {
                                $money8 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                $number8++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money8, 5, 'V2业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money8 = RETAIN_TWO($money8 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                $number8++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money8, 5, 'V2业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                }
            }
            //更新会员数据
            $UserModel->where(['uid' => $v['uid']])->update($v);
        }
        return true;
    }


    /**
     * 微商城升级处理
     * @param $v 会员数据
     * @param $puid 上级会员
     * @param $ExceedShop 超级商城设置
     * @return mixed 返回会员数据
     */
    public function microGrade($v, $puid, $ExceedShop, $array = array(), $share, $money, $setBonus, $actual_money)
    {
//        //微商城设置
//        $microMall = new MicroMall();
//        $micro = $microMall->get()->toArray();
        //业绩设置
//        $QualityModel = new SetQuality();
//        $Quality = $QualityModel->get()->toArray();
        $v['super_team_count'] += $actual_money;
        //添加小区团队业绩
        $super_small_team_count = json_decode($v['super_small_team_count'], true);
        if ($super_small_team_count) {   //判断是否已有团队业绩
            foreach ($super_small_team_count as $items => $item) {
                if ($share == $v['uid']) {
                    if (isset($super_small_team_count[$puid]) && $items == $puid) {

                        $super_small_team_count[$puid]['money'] += $actual_money;
                    } elseif (!isset($super_small_team_count[$puid])) {
                        $super_small_team_count[$puid] = [
                            'key' => $puid,
                            'val' => 1,
                            'money' => $actual_money,
                        ];
                    }

                }
                if (isset($array[$items]) ? $array[$items] : 0) {
                    $super_small_team_count[$items]['money'] += $actual_money;
                }
            }
            $super_small_team_count = json_encode($super_small_team_count);
        }

        $v['super_small_team_count'] = $super_small_team_count; //添加小区团队
        /*--------------------------------------**/
        //直推人数查询  这里查询应该有问题  要不然就是你绑定哪里出了问题
        $realTeamCount = Members::where(['referrer' => $v['uid']])->select('uid')->count();
        $v['super_recommend'] = $realTeamCount;
        // 加权分红
        if ($v['tiny_level'] == 0) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if (($v['super_team_count'] >= $setBonus[0]['team_count']) && ($counts >= $setBonus[0]['small_team_count'])) {
                    $v['tiny_level_name'] = $setBonus[0]['level_name'];
                    $v['tiny_level'] = $setBonus[0]['id'];
                }
            }

        }
        //V2
        if ($v['tiny_level'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if (($v['super_team_count'] >= $setBonus[1]['team_count']) && ($counts >= $setBonus[1]['small_team_count'])) {
                    $v['tiny_level_name'] = $setBonus[1]['level_name'];
                    $v['tiny_level'] = $setBonus[1]['id'];
                }
            }
        }

        //V3
        if ($v['tiny_level'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if (($v['super_team_count'] >= $setBonus[2]['team_count']) && ($counts >= $setBonus[2]['small_team_count'])) {
                    $v['tiny_level_name'] = $setBonus[2]['level_name'];
                    $v['tiny_level'] = $setBonus[2]['id'];
                }
            }
        }
//        if ($v['level'] == 0){//v1
//            if ($v['super_team_count'] >= $Quality[0]['team_count']){
//                $v['level_name'] = $Quality[0]['level_name'];
//                $v['level'] = $Quality[0]['level'];
//                $v['level_grade'] = $Quality[0]['level_stage'];
//            }
//        }
//
//        if ($v['level'] == 1 && $v['level_grade'] == 1) {
//            if ($v['super_team_count'] >= $Quality[1]['team_count']) {
//                $v['level_grade'] = $Quality[1]['level_stage'];
//            }
//        }
//
//        if ($v['level'] == 1 && $v['level_grade'] == 2) {
//            if ($v['super_team_count'] >= $Quality[2]['team_count']) {
//                $v['level_grade'] = $Quality[2]['level_stage'];
//            }
//        }
//
//        if ($v['level'] == 1 && $v['level_grade'] == 3) {
//            $super_small_team_count = json_decode($v['super_small_team_count'], true);
//            if ($super_small_team_count) {
//                //重组数组
//                $arrSort = array();
//                foreach ($super_small_team_count as $uniqid => $row) {
//                    foreach ($row as $key => $value) {
//                        $arrSort[$key][$uniqid] = $value;
//                    }
//                }
//                $big_team = 0; //满足业绩小区个数
//                foreach ($super_small_team_count as $items => $item) {
//                    //计算大小区
//                    if ($item['money'] >= $Quality[3]['big_team_count']) {
//                        $big_team += 1;
//                    }
//                }
//                if ($big_team >= $Quality[3]['big_team']){
//                    $v['level_name'] = $Quality[3]['level_name'];
//                    $v['level'] = $Quality[3]['level'];
//                    $v['level_grade'] = $Quality[3]['level_stage'];
//                }
//            }
//        }
//
//        if ($v['level'] == 2  && $v['level_grade'] == 1){
//            $super_small_team_count = json_decode($v['super_small_team_count'], true);
//            if ($super_small_team_count) {
//                //重组数组
//                $arrSort = array();
//                foreach ($super_small_team_count as $uniqid => $row) {
//                    foreach ($row as $key => $value) {
//                        $arrSort[$key][$uniqid] = $value;
//                    }
//                }
//                $big_team = 0; //满足业绩小区个数
//                foreach ($super_small_team_count as $items => $item) {
//                    //计算大小区
//                    if ($item['money'] >= $Quality[4]['big_team_count']) {
//                        $big_team += 1;
//                    }
//                }
//                if ($big_team >= $Quality[4]['big_team']){
//                    $v['level_grade'] = $Quality[4]['level_stage'];
//                }
//            }
//        }
//
//        if ($v['level'] == 2  && $v['level_grade'] == 2){
//            $super_small_team_count = json_decode($v['super_small_team_count'], true);
//            if ($super_small_team_count) {
//                //重组数组
//                $arrSort = array();
//                foreach ($super_small_team_count as $uniqid => $row) {
//                    foreach ($row as $key => $value) {
//                        $arrSort[$key][$uniqid] = $value;
//                    }
//                }
//                $big_team = 0; //满足业绩小区个数
//                foreach ($super_small_team_count as $items => $item) {
//                    //计算大小区
//                    if ($item['money'] >= $Quality[5]['big_team_count']) {
//                        $big_team += 1;
//                    }
//                }
//                if ($big_team >= $Quality[5]['big_team']){
//                    $v['level_grade'] = $Quality[5]['level_stage'];
//                }
//            }
//        }
//
//        if ($v['level'] == 2  && $v['level_grade'] == 3){
//            $super_small_team_count = json_decode($v['super_small_team_count'], true);
//            if ($super_small_team_count) {
//                //重组数组
//                $arrSort = array();
//                foreach ($super_small_team_count as $uniqid => $row) {
//                    foreach ($row as $key => $value) {
//                        $arrSort[$key][$uniqid] = $value;
//                    }
//                }
//                $big_team = 0; //满足业绩小区个数
//                foreach ($super_small_team_count as $items => $item) {
//                    //计算大小区
//                    if ($item['money'] >= $Quality[6]['big_team_count']) {
//                        $big_team += 1;
//                    }
//                }
//                if ($big_team >= $Quality[6]['big_team']){
//                    $v['level_name'] = $Quality[6]['level_name'];
//                    $v['level'] = $Quality[6]['level'];
//                    $v['level_grade'] = $Quality[6]['level_stage'];
//                }
//            }
//        }

        return $v;
    }

    /**
     * 微商城会员订单之前的奖金币金额记录
     * @param null $uid 会员id
     * @param string $ordersn 统一订单
     */
    public function bonusCredit2($uid, $ordersn)
    {
        $UserModel = new Members();
        $ShopOrder = new ShopOrder();
        $memberLastCredit2Datas = $ShopOrder->where(['ordersn' => $ordersn])->value('last_credit2s');
        if ($memberLastCredit2Datas) {
            $memberLastCredit2Datas = unserialize($memberLastCredit2Datas);
        } else {
            $memberLastCredit2Datas = [];
        }
        $memberLastCredit2Id = [];
        $memberLastCredit2 = [];
        $memberLastCredit2Data = [];
        $memberLastData = $UserModel->where(['uid' => $uid])->select('uid', 'name', 'user_name', 'credit1', 'credit2', 'credit4')->first();
        $memberLastCredit2Data['uid'] = $memberLastData['uid'];
        $memberLastCredit2Data['name'] = $memberLastData['name'];
        $memberLastCredit2Data['user_name'] = $memberLastData['user_name'];
        $memberLastCredit2Data['credit1'] = $memberLastData['credit1'];
        $memberLastCredit2Data['credit2'] = $memberLastData['credit2'];
        $memberLastCredit2Data['credit4'] = $memberLastData['credit4'];

        if ($memberLastCredit2Data) {
            if ($memberLastCredit2Datas && count($memberLastCredit2Datas) > 0) {
                foreach ($memberLastCredit2Datas as $key => $value) {
                    if (!in_array($value['uid'], $memberLastCredit2Id)) {
                        array_push($memberLastCredit2Id, $value['uid']);
                    }
                }
            }
            if (!in_array($uid, $memberLastCredit2Id)) {
                array_push($memberLastCredit2Datas, $memberLastCredit2Data);
                array_push($memberLastCredit2Id, $uid);
            }
        }
        if ($memberLastCredit2Datas) {
            $ShopOrder->where(['ordersn' => $ordersn])->update(['last_credit2s' => serialize($memberLastCredit2Datas)]);
        }


    }


    /**
     *今日签到
     */
    public function dosign()
    {
        //获取用户
        $user = session('home_user');
        //查询用户
        $signInfo = MemberSign::where('uid', $user['uid'])->first();
        //用户ID
        $data['uid'] = $user['uid'];
        //最后签到时间
        $data['last_sign_time'] = time();
        //如果用户不存在插入签到 存在更新积分
        if (!$signInfo) {
            if (MemberSign::create($data)) {
                //当前用户的积分
                $userData = Members::where('uid', $user['uid'])->first();
                $signData['credit4'] = $userData['credit4'] + 1;
                $res = Members::where('uid', $user['uid'])->update(array_only($signData, ['credit4']));
                return ['code' => 1, 'data' => '签到成功+1积分', 'status' => 1];
            } else {
                return ['code' => 0, 'data' => '签到失败'];
            }
        } else {
            //当前时间
            $signTime = time();
            //计算时间差值
            $checkSign = timediff($signInfo['last_sign_time'], $signTime);
            if ($checkSign['day'] == 0) {
                return ['code' => 0, 'data' => '您今日已经签过到了'];
            } else if ($checkSign['day'] == 1) {
                $userData = Members::where('uid', $user['uid'])->first();
                $signData['credit4'] = $userData['credit4'] + 1;
                $res = Members::where('uid', $user['uid'])->update(array_only($signData, ['credit4']));
                if ($res) {
                    $resData['last_sign_time'] = time();
                    if (MemberSign::where('uid', $user['uid'])->update(array_only($resData, ['last_sign_time']))) {
                        return ['code' => 1, 'data' => '签到成功+1积分', 'status' => 1];
                    } else {
                        return ['code' => 0, 'data' => '签到失败'];
                    }
                }
            }
        }
    }

    /**
     * 检测是否签到
     */
    public function findsign()
    {
        //获取用户
        $user = session('home_user');
        //查询用户
        $signInfo = MemberSign::where('uid', $user['uid'])->first();
        //如果用户不存在插入签到 存在更新积分
        if ($signInfo) {
            //当前时间
            $signTime = time();
            //计算时间差值
            $checkSign = timediff($signInfo['last_sign_time'], $signTime);
            if ($checkSign['day'] == 0) {
                //已签到
                return ['status' => 1];
            } else if ($checkSign['day'] == 1) {
                //未签到
                return ['status' => 2];
            }
        } else {
            return ['status' => 2];
        }
    }

    /**
     * 财务列表
     */
    public function dofinance(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        $MemberData = Members::where('uid', $user['uid'])->first();
        if ($data['type'] == 'z') {
            $MemberData['userType'] = 'z';
            $MemberLevel = MembersLevel::where('id', $MemberData['level'])->first();

        } elseif ($data['type'] == 'w') {
            $MemberData['userType'] = 'w';
            $MemberLevel = MicroMall::where('id', $MemberData['tiny_level'])->first();
            $MemberData['level_name'] = $MemberLevel['vip_name'];

        } elseif ($data['type'] == 'c') {
            $MemberData['userType'] = 'c';
            $MemberLevel = ExceedShop::where('id', $MemberData['super_level'])->first();
            $MemberData['level_name'] = $MemberLevel['vip_name'];
            $MemberData['super_team_count'] = intval($MemberData['super_team_count'] / 99);

        }
        if ($MemberData) {
            return ['code' => 1, 'data' => $MemberData];
        } else {
            return ['code' => 0, 'data' => '暂无数据'];
        }
    }


    /**
     * @param Request $request
     * @return array
     * 发送系统公告
     */
    public function notice()
    {
        $notice = Notice::where('is_publish', 1)->get()->toArray();
//        var_dump($notice);exit;
        $arr = array();
        foreach ($notice as $k => $v) {
            if (strtotime($v['release_time']) <= time() && strtotime($v['deadline']) >= time()) {
                $arr[] = $notice[$k];
            }
        }
        if (!empty($arr)) {
            return ['code' => 1, 'data' => $arr];
        } else {
            return ['code' => 0, 'data' => '暂无公告'];
        }
    }

    /**
     * //将以前已开通直商城的用户的复投币转入直商城复投币单独保存
     *
     */
    public function transform()
    {
        //获取所有直商城用户
        $memberModel = new Members();
        $memberData = $memberModel->getStraightMembers();
        foreach ($memberData as $key => $value) {
            if ($value['credit3'] > 0) {
                $saveData = [
                    'credit3' => 0,
                    'credit6' => $value['credit3']
                ];
                $res = Members::where('uid', $value['uid'])->update($saveData);
                if (!$res) {
                    return ['code' => 0, 'data' => '修改失败'];
                }
            }
        }
        return 'ok';
    }

    /**
     *分公司管理
     */
    public function agent()
    {

        return view('Home.member.branch');
    }

    public function agentList()
    {
        $user = session('home_user');
        $agent = Apply::where(['uid' => $user['uid'], 'status' => 1])->first();
        if ($agent['type'] == 0) {
            $agent['type'] = '省代理';
        } else if ($agent['type'] == 1) {
            $agent['type'] = '市代理';
        } else {
            $agent['type'] = '区/县代理';
        }
        $agent['district'] = json_decode($agent['district'], true);
        if ($agent) {
            return ['code' => 1, 'data' => $agent];
        } else {
            return ['code' => 0, 'data' => '暂无代理权限'];
        }
    }

    public function partner()
    {
        $user = session('home_user');
        $agent = Apply::join('set_rebate', 'set_rebate.a_id', '=', 'user_apply.id')
            ->join('members', 'members.name', '=', 'set_rebate.name')
            ->select('set_rebate.*',
                'user_apply.id',
                'members.super_team_count',
                'members.name',
                'members.referrer',
                'members.uid'
            )
            ->where('user_apply.uid', $user['uid'])
            ->get()
            ->toArray();
        foreach ($agent as $k => $v) {
            $agent[$k]['super_recommend'] = Members::where('referrer', $v['uid'])->count();
        }
        if ($agent) {
            return ['code' => 1, 'data' => $agent];
        } else {
            return ['code' => 0, 'data' => '暂无代理权限'];
        }
    }

    public function line()
    {
        return view('Home.member.line');
    }

    public function addPerformance()
    {
//        $orders =  Members::where('uid','>',20)->where('super_level','>=',2)->count();
//        $count = Members::where('uid','>',20)->sum('credit4');
//        var_dump($orders);
//        var_dump($count);die;
        //系统设置
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->get()->toArray();
        //业绩设置
        $QualityModel = new SetQuality();
        $Quality = $QualityModel->get()->toArray();
        $orderData = ShopOrder::where('id', 93)->get()->toArray();
//        $memberData = Members::where('super_level','>=',2)->offset(300)->limit(100)->orderby('uid','asc')->get()->toArray();
        foreach ($orderData as $key => $value) {
            $referrer = Members::where('uid', $value['uid'])->value('referrer');
//            $share = $value['referrer'];//分享人ID
//            $puid = $value['uid'];
//            $arrays = [];
            $res = $this->achievementBonus($value['uid'], $referrer, $Quality, $Poundage, 2000, '');
//            $members = Members::where('uid', '<=', $value['uid'])->orderBy('uid', 'desc')->select('uid', 'referrer','level','level_name', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement')->get()->toArray();
//            foreach ($members as $k => $v) {

//                if (!empty($v['referrer'])) {
//                    if ($referrer == $v['uid']) {//寻找上级id 微客
//                        $referrer = $v['referrer'];
//                        //会员等级升级
//                        $arrays[$v['uid']] = $v['referrer'];
//                        $v = $this->UpGrade($v, $puid, $ExceedShop, $Quality, $arrays, $share, 2000, 2);
//                    }
//                    Members::where('uid',$v['uid'])->update($v);
//                }
//            }
        }
//        //系统设置
//        $PoundageModel = new Poundage();
//        $Poundage = $PoundageModel->find_poundage();
//        //超级商城设置
//        $ExceedShopModel = new ExceedShop();
//        $ExceedShop = $ExceedShopModel->get()->toArray();
//        //业绩设置
//        $QualityModel = new SetQuality();
//        $Quality = $QualityModel->get()->toArray();
//        $memberData = Members::where('super_level','>=',2)->where('uid' ,'>=',300)->where('uid','<',400)->orderby('uid','asc')->get()->toArray();
//        foreach ($memberData as $key => $value){
//            $referrer = $value['referrer'];
//            $share = $value['referrer'];//分享人ID
//            $puid = $value['uid'];
//            $arrays = [];
//            $members = Members::where('uid', '<=', $value['uid'])->orderBy('uid', 'desc')->select('uid', 'referrer','level','level_name', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement')->get()->toArray();
//            foreach ($members as $k => $v) {
//                if (!empty($v['referrer'])) {
//                    if ($referrer == $v['uid']) {//寻找上级id 微客
//                        $referrer = $v['referrer'];
//                        //会员等级升级
//                        $arrays[$v['uid']] = $v['referrer'];
//                        $v = $this->UpGrade($v, $puid, $ExceedShop, $Quality, $arrays, $share, 2000, 2);
//                    }
//                    Members::where('uid',$v['uid'])->update($v);
//                }
//            }
//        }
    }

    /**
     * 转账验证码
     */
    public function yzx(Request $request)
    {
        $phone = $request->get('name');
        if (session('sms' . $phone)['time'] > time()) {
            return ['code' => 0, 'data' => '请一分钟后重试'];
        }
        $rand = rand(100000, 999999);
        $url = 'http://open2.ucpaas.com/sms-server/variablesms';
        $body_json = array(
            "clientid" => "b15593",
            "password" => "d969859f052d5effb353334c3523844c",
            "mobile" => "$phone",
            "templateid" => "3781",
            'param' => "$rand",
        );
        $data = httpRequest($url, 'post', json_encode($body_json));
        $datas = json_decode($data, true);
        if ($datas['code'] == "0") {
            Session::put('registers_code' . $phone, [
                'rand' => $rand,
                'time' => time() + 60 * 5
            ]);
            return ['code' => 1, 'data' => '获取验证码成功'];
        } else {
            return ['code' => 0, 'data' => $datas['msg']];
        }

    }

    /**
     * 提现验证码
     */
    public function yzxSms(Request $request)
    {

        $phone = $request->get('name');
        if (session('sms' . $phone)['time'] > time()) {
            return ['code' => 0, 'data' => '请一分钟后重试'];
        }
        $rand = rand(100000, 999999);
        $url = 'http://open2.ucpaas.com/sms-server/variablesms';
        $body_json = array(
            "clientid" => "b15593",
            "password" => "d969859f052d5effb353334c3523844c",
            "mobile" => "$phone",
            "templateid" => "3780",
            'param' => "$rand",
        );
        $data = httpRequest($url, 'post', json_encode($body_json));
        $datas = json_decode($data, true);
        if ($datas['code'] == "0") {
            Session::put('register_code' . $phone, [
                'rand' => $rand,
                'time' => time() + 60 * 5
            ]);
            return ['code' => 1, 'data' => '获取验证码成功'];
        } else {
            return ['code' => 0, 'data' => $datas['msg']];
        }

    }

    /*
* 注册验证码
*/
    public function registerSms(Request $request)
    {

        $phone = $request->get('name');
        $user = session('home_user');
        if ($user['name'] == $phone) {
            return ['code' => 0, 'data' => '注册账号不能是本账号！'];
        }
        if (session('sms' . $phone)['time'] > time()) {
            return ['code' => 0, 'data' => '请一分钟后重试'];
        }
        $rand = rand(100000, 999999);
        $url = 'http://open2.ucpaas.com/sms-server/variablesms';
        $body_json = array(
            "clientid" => "b15593",
            "password" => "d969859f052d5effb353334c3523844c",
            "mobile" => "$phone",
            "templateid" => "3779",
            'param' => "$rand",
        );
        $data = httpRequest($url, 'post', json_encode($body_json));
        $datas = json_decode($data, true);
        if ($datas['code'] == "0") {
            Session::put('register_code' . $phone, [
                'rand' => $rand,
                'time' => time() + 60 * 5
            ]);
            return ['code' => 1, 'data' => '获取验证码成功'];
        } else {
            return ['code' => 0, 'data' => $datas['msg']];
        }

    }

    /*
     * 我的团队
     */
    public function team()
    {
        $user = session('home_user');
        $UserModel = new Members();
        $members = $UserModel->where(['referrer' => $user['uid'], 'registered' => 1])->orderBy('uid', 'asc')->get()->toArray();
        foreach ($members as &$v) {

            $v['enroll_time'] = date("Y-m-d", $v['enroll_time']);
        }
        if ($members) {
            return ['code' => 1, 'data' => $members];
        } else {
            return ['code' => 0, 'data' => '暂无团队'];
        }
    }

    /**
     *
     * 会员充值
     */
    public function recharge()
    {

        return view('Home.member.recharge');
    }
}


